confirmLoad = function() {
    $("#viewport").addClass("is-loaded");
}

$(document).ready(
	function() {
	    confirmLoad();
	    attachAnchorBehaviour();
	    if ($.browser.msie) {
	        stylePulledContent();
	    }
	}
);

stylePulledContent = function() {
    $(".pull").each(function(index) {
        var width = $(this).children("img").width();
        if (width != 0) {
            $(this).css("width", width);
        }
    });
}

$(".pull img").load(function() {
    var width = $(this).width();
    $(this).parent().css("width", width);
});

inert_init = function()
{
 $(".inert")
 .hover(function()
 {
  var titleValue = "This link is temporarily inactive.";
  this.title = titleValue;
  //alert('hello');
})
 .click(function(){return false;});
}

$(document).ready(inert_init);

sizeSiteWideSearch = function() {
    var mastheadWidth = $("#masthead .wrapper").width();
    var navigationWidth = 640;
    var offSet = 30;
    var buttonWidth = 37;

    var searchWidth = (mastheadWidth - navigationWidth) - offSet + "px";
    var searchInputWidth = (mastheadWidth - navigationWidth) - (offSet + buttonWidth) + "px";

    $("#masthead fieldset").css("width", searchWidth);
    $("#masthead fieldset #txt-search").css("width", searchInputWidth);
    $("#masthead fieldset").css("visibility", "visible");
}

$(window).bind("load resize", function()
{
    sizeSiteWideSearch();
});

attachAnchorBehaviour = function() {
    $("a[href$='.pdf'], a[href$='.doc'], a[href$='.xls'], a[href$='.ppt'], a[href$='.zip']").each(function(index) {
        var hrefParts = this.href.split(".");
        var fileType = hrefParts[hrefParts.length - 1].toUpperCase();

        var titleValue = "Click to download " + fileType;

        this.title = titleValue;

    }).click(function(event) {
        openWindow(this.href);
        return false;
    });

    $("a[href^='http://'], a[href^='https://']").each(function(index) {
        var titleValue = "(Opens in new window/tab)";
        this.title = titleValue;
    }).click(function(event) {
        openWindow(this.href);
        return false;
    });

    $("a[rel]").each(function(index) {
        switch (this.rel) {
            case 'external':
                this.title = "Link launches in new window";
                break;
        }
    }).click(function(event) {
        switch (this.rel) {
            case 'nofollow': case 'external':
                openWindow(this.href);
                return false;
                break;

            case 'within-page':
                scrollToSelector(this.href);
                return false;
                break;
        }
    });
}

// ----------------------------------------------
scrollToSelector = function(href) {
    var modifiedHref = href.substring(href.indexOf("#") + 1);
    var targetOffset = $("#" + modifiedHref).offset().top;

    $("html,body").animate(
    {
        scrollTop: targetOffset
    }, 1000);
}

$(document).ready(function() {
    /*var loc = window.location;

    var prot = new Array();
    prot = window.location.href.split("//");

    var sections = new Array();
    sections = prot[1].split("/");

    if (sections.length > 1) {
        var lis = document.getElementById('navigation').getElementsByTagName("li");
        for (var i = 0; i < lis.length; i++) {
            if ("nav-" + sections[1].replace(" ", "-").toLowerCase() == lis[i].id.toLowerCase()) {
                lis[i].className = lis[i].className + " selected";
            }
            else {
                lis[i].className = lis[i].className.replace(" selected", "");
            }
        }
    }*/
});

(function($) {
    $.fn.hint = function(blurClass) {
        if (!blurClass) {
            blurClass = 'blur';
        }
        return $(".hint").each(function() {
            // get jQuery version of 'this'
            var $input = $(this),

            // capture the rest of the variable to allow for reuse
			title = $input.attr('title'),
			$form = $(this.form),
			$win = $(window);

            remove = function() {
                if ($input.val() === title && $input.hasClass(blurClass)) {
                    $input.val('').removeClass(blurClass);
                }
            }
            // only apply logic if the element has the attribute
            if (title) {
                // on blur, set value to title attr if text is blank
                $input.blur(function() {
                    if (this.value === '') {
                        $input.val(title).addClass(blurClass);
                    }
                }).focus(remove).blur(); // now change all inputs to title

                // clear the pre-defined text when form is submitted
                $form.submit(remove);
                $win.unload(remove); // handles Firefox's autocomplete
            }
        });
    };
})(jQuery);

$(function() {
    $('input[title!=""]').hint();
});

// Mega Menus
// ----------------------------------------------
var viewport_listener_timer_id = 0;
var current_dropdown_open = "";
var timer_id = 0;
var dropdown_menu_timer_id = 0;

$(document).ready(function() {
    $('#navigation li').mouseover(function(event) {
        
        clearInterval(timer_id);
        //clearInterval(viewport_listener_timer_id);
        var id = this.id.replace("nav-", "");
        var remove_viewport_listener = true;

        //viewport_listener_timer_id = setInterval("removeMegaMenu()", 500);

        //        $(".navigation-dropdown").each(function(index) {
        //            var dropdown_id = this.id.replace("-dropdown", "");

        //            if (dropdown_id != id) {
        //                if (dropdown_id == current_dropdown_open) {
        //                    this.style.display = "none";
        //                    $("#navigation li#nav-" + dropdown_id).removeClass("active");
        //                    $("#viewport-listener").unbind("mouseover").remove();
        //                }
        //            }
        //        });

        if (this.className.indexOf("has-dropdown") >= 0) {
            timer_id = setInterval("mouseOverItem('" + id + "')", 500);
        }
        else {
            //viewport_listener_timer_id = setInterval("removeMegaMenu()", 500);
            timer_id = setInterval("removeMegaMenu()", 500);
        }
    });

    $("#navigation li").mouseout(function(event) {
        clearInterval(timer_id);
    });

    $(".navigation-dropdown-inner").mouseover(function(event) {
        clearInterval(timer_id);
        //clearInterval(viewport_listener_timer_id);
    });

    $(".drop-down-menu-content").css("display", "none");

    $(".trigger").not(".type-03").mouseover(function(event) {
        var id = $(this).parent().get(0).id;
        dropdown_menu_timer_id = setInterval("triggerDropdown('" + id + "')", 500);
    });

    $(".trigger").not(".type-03").click(function(event) {
        var id = $(this).parent().get(0).id;
        triggerDropdown(id);
        return false;
    });

    fadeInSequence = function(id, iteration) {
        var number_items = $("#" + id + " ul li a").length;
        if (iteration < number_items) {
            $("#" + id + " ul li.drop-down-menu-item a").eq(iteration).fadeIn(50, function() {
                fadeInSequence(id, iteration + 1);
            });
        }
    }

    $(".drop-down-menu").mouseout(function(event) {
        clearInterval(timer_id);
        clearInterval(dropdown_menu_timer_id);

        if (event.relatedTarget != null) {
            var event_class = event.relatedTarget.className;
            var close = true;

            if (event_class.indexOf("drop-down-menu-item") >= 0) {
                close = false;
            }

            if (close) {
                if (event_class.indexOf("drop-down-menu-content") >= 0) {
                    close = false;
                }
            }

            if (close) {
                if (event_class.indexOf("trigger") >= 0) {
                    close = false;
                }
            }

            if (close) {
                if (event_class.indexOf("drop-down-options") >= 0) {
                    close = false;
                }
            }

            if (close) {
                $("#" + this.id + " ul").slideUp("fast");
                $("#" + this.id + " ul li.drop-down-menu-item a").css("display", "none");
            }
        }
    });

    //    tooltip_init();
});

triggerDropdown = function(id) {
    clearInterval(dropdown_menu_timer_id);
    $("#" + id + " ul").slideDown("fast");
    fadeInSequence(id, 0);
}

mouseOverItem = function(id) {
    //alert("mouseover");
    //$("#viewport-listener").unbind("mouseover").remove();
    clearInterval(timer_id);
    //clearInterval(viewport_listener_timer_id);
    $("#navigation li").removeClass("active");
    $(".navigation-dropdown").css("display", "none");
    $("#navigation li#nav-" + id).addClass("active");
    $("#" + id + "-dropdown").css("display", "block");
    current_dropdown_open = id.replace("nav-", "");
    addViewportListener();
}

mouseOverViewportListener = function(relatedTargetid) {

    clearInterval(timer_id);
    //clearInterval(viewport_listener_timer_id);
    var remove_viewport_listener = true;
    var id = relatedTargetid.replace("nav-", "");
    $(".navigation-dropdown").each(function(index) {
        this.style.display = "none";
    });

    if (remove_viewport_listener) {
        $("#viewport-listener").unbind("mouseover").remove();
        $("#navigation li").removeClass("active");
    }

}



addViewportListener = function() {
    //clearInterval(viewport_listener_timer_id);
    if ($("#viewport-listener").length == 0) {
        var viewport = $("div#viewport");
        viewport.append("<div id='viewport-listener'></div>");
        $("#viewport-listener").css("width", viewport.width()).css("height", viewport.height()).mouseover(function(event) {
            //alert("mouseovervp");
            clearInterval(timer_id);
            //            if (event.relatedTarget != null) {
            //                //alert(event.relatedTarget.className);
            //                //viewport_listener_timer_id = setInterval("mouseOverViewportListener('" + event.relatedTarget.id + "')", 100);
            //                viewport_listener_timer_id = setInterval("removeMegaMenu()", 500);
            //            }
            //            else {
            //clearInterval(timer_id);
            //alert("viewportlistener");
            //viewport_listener_timer_id = setInterval("removeMegaMenu()", 500);
            timer_id = setInterval("removeMegaMenu()", 500);

            //}
        });
    }
}

removeMegaMenu = function() {

    //clearInterval(viewport_listener_timer_id);
    clearInterval(timer_id);
    $(".navigation-dropdown").css("display", "none");
    $("#viewport-listener").unbind("mouseover").remove();
    $("#navigation li").removeClass("active");
}

//viewport_listener_timer_id = setInterval("removeMegaMenu()", 500);

getElementWidth = function(objectId) {
    x = document.getElementById(objectId);
    return x.offsetWidth;
}

getAbsoluteLeft = function(objectId) {
    // Get an object left position from the upper left viewport corner
    o = document.getElementById(objectId)
    oLeft = o.offsetLeft            // Get left position from the parent object
    
    while (o.offsetParent != null) {
        // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent    // Get parent object reference
        
        oLeft += oParent.offsetLeft // Add parent left position
        
        o = oParent
    }

    return oLeft;
}

getAbsoluteLeftObject = function(o) {
    // Get an object left position from the upper left viewport corner
    //o = document.getElementById(objectId)
    oLeft = o.offsetLeft            // Get left position from the parent object

    while (o.offsetParent != null) {
        // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent    // Get parent object reference

        oLeft += oParent.offsetLeft // Add parent left position

        o = oParent
    }

    return oLeft;
}


getAbsoluteTop = function(objectId) {
    // Get an object top position from the upper left viewport corner
    o = document.getElementById(objectId)
    oTop = o.offsetTop            // Get top position from the parent object
    while (o.offsetParent != null) {
        // Parse the parent hierarchy up to the document element
        oParent = o.offsetParent  // Get parent object reference
        oTop += oParent.offsetTop // Add parent top position
        o = oParent
    }
    return oTop;
}

parseQuery = function(query) {
    var Params = new Object();
    if (!query) return Params; // return empty object
    var Pairs = query.split(/[;&]/);
    for (var i = 0; i < Pairs.length; i++) {
        var KeyVal = Pairs[i].split("=");
        if (!KeyVal || KeyVal.length != 2) continue;
        var key = unescape(KeyVal[0]);
        var val = unescape(KeyVal[1]);
        val = val.replace(/\+/g, ' ');
        Params[key] = val;
    }
    return Params;
}

function blockEvents(evt) {
    if (evt.target) {
        evt.preventDefault();
    }
    else {
        evt.returnValue = false;
    }
}


//Share Link
//E-Updates

$("a").each(function() {

    if (this.innerHTML == "Share") {
        $(this).click(function() {

            //Set Share attributes

            var doc_title = encodeURI(document.title);
            var doc_url = encodeURI(document.URL);

            //Linked In
            $("a.linkedin").attr("href", "http://www.linkedin.com/shareArticle?mini=true&url=" + doc_url + "&title=" + doc_title);

            //Facebook
            $("a.facebook").attr("href", "http://www.facebook.com/sharer.php?u=" + doc_url + "&t=" + doc_title);

            //Digg
            $("a.digg").attr("href", "http://digg.com/submit?phase=2&url=" + doc_url + "&title=" + doc_title);

            //MySpace
            $("a.myspace").attr("href", "http://www.myspace.com/index.cfm?fuseaction=postto&u=" + doc_url + "&t=" + doc_title);

            //Twitter
            $("a.twitter").attr("href", "http://twitter.com/home?status=Currently reading " + doc_url);

            //Delicious
            $("a.delicious").attr("href", "http://delicious.com/save?v=5&noui&jump=close&url=" + doc_url + "&title=" + doc_title);

            this.id = "a-share";


            var containerId = "social-bookmarks";

            var containerElementx = getAbsoluteLeft(containerId);
            var containerWidth = $("#" + containerId).width();

            var tip_width = $("#" + containerId).width();
            var tip_height = $("#" + containerId).height();

            var tooltipX = getAbsoluteLeft(this.id); //set x position
            var tooltipY = getAbsoluteTop(this.id) + $('#' + this.id).height() + 25;

            $("#" + containerId).css({ left: tooltipX - 160 + "px", top: tooltipY + "px" });

            $("#" + containerId).fadeIn("fast");

            $("a.close").click(function() {
                $("#" + containerId).hide();
                return false;
            });

            return false;
        });

    }
    if (this.innerHTML == "Sign Up") {
        $(this).click(function() {

            this.id = "a-share";

            var containerId = "e-updates";

            var containerElementx = getAbsoluteLeft(containerId);
            var containerWidth = $("#" + containerId).width();

            var tip_width = $("#" + containerId).width();
            var tip_height = $("#" + containerId).height();

            var tooltipX = getAbsoluteLeftObject(this); //set x position
            var tooltipY = getAbsoluteTop(this.id) + $('#' + this.id).height() + 25;

            $("#" + containerId).css({ left: tooltipX - 350 + "px", top: tooltipY + "px" });

            resetAllFields("sign-up-content");
            resetAllErrors();
            $("#sign-up-content").show();
            $("#sign-up-confirmed").hide();
            
            $("#" + containerId).fadeIn("fast");

            $("#submit-sign-up").click(function() {
                submitSignUp();
            });

            $("a.close").click(function() {
                resetAllFields("sign-up-content");
                resetAllErrors();
                $("#" + containerId).hide();
                return false;
            });

            return false;
        });

    }
});

submitSignUp = function() {

    resetAllErrors();

    var valid_fname = validateField("txt-first-name", "input-required", "First Name Required");
    var valid_lname = validateField("txt-last-name", "input-required", "Last Name Required");
    var valid_email = validateField("txt-email", "input-email", "Valid Email Required");
    var valid_country = validateField("dd-country", "input-select", "Please Choose a Country");
    var valid_subscriber = validateField("rad-type-of-subscriber", "input-radio", "Please Select One Of The Following");

    if (valid_subscriber) {
        switch ($("input:radio[name=rad-type-of-subscriber]:checked").val()) {
            case "I am a member of the press":
                var valid_outlet = validateField("txt-outlet", "input-required", "Required");
                var valid_beat = validateField("txt-beat", "input-required", "Required");
                valid_subscriber = (valid_outlet && valid_beat);
                break;
            case "I am a grantee":
                valid_subscriber = validateField("txt-organization", "input-required", "Organization Required");
                break;
            case "Other":
                valid_subscriber = validateField("dd-type-of-subscriber-is-other", "input-select", "Other Required");
                break;
        }
    }

    if ((valid_fname && valid_lname && valid_email && valid_country && valid_subscriber)) {
        //form fields are valid

        var firstname = $("#txt-first-name").val();
        var lastname = $("#txt-last-name").val();
        var email = $("#txt-email").val();
        var country = $("#dd-country option:selected").val()
        var subscriber = $("input:radio[name=rad-type-of-subscriber]:checked").val()
        var outlet = $("#txt-outlet").val();
        var beat = $("#txt-beat").val();
        var organization = $("#txt-organization").val();
        var other = $("input:radio[name=dd-type-of-subscriber-is-other]:checked").val()

        var post_url = "/about-us/submitsignupform?firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&country=" + country + "&subscriber=" + subscriber + "&outlet=" + outlet + "&beat=" + beat + "&organization=" + organization + "&other=" + other;

        $.post(post_url, "",
                function(results) {
                    if (results) {
                        $("#sign-up-content").hide();
                        $("#sign-up-confirmed").show();
                    }
                }, "json");

    }
    else {

    }
}

validateField = function(selectorID, validationType, invalidMessage) {

    var field_valid = false;

    switch (validationType) {
        case "input-required":
            if ($("#" + selectorID).val() != null) {
                if ($("#" + selectorID).val() == "") {
                    setFieldErrorSpan(selectorID, invalidMessage, true);
                }
                else {
                    setFieldErrorSpan(selectorID, "", false);
                    field_valid = true;
                }
            }
            else {
                setFieldErrorSpan(selectorID, invalidMessage, true);
            }
            break;
        case "input-email":
            var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if (reg.test($("#" + selectorID).val()) == false) {
                setFieldErrorSpan(selectorID, invalidMessage, true);
            }
            else {
                setFieldErrorSpan(selectorID, "", false);
                field_valid = true;
            }

            break;
        case "input-select":

            if ($("#" + selectorID + " option:selected").val() == "invalid") {
                setFieldErrorSpan(selectorID, invalidMessage, true);
            }
            else {
                setFieldErrorSpan(selectorID, "", false);
                field_valid = true;
            }
            break;
        case "input-radio":
            if ($("input:radio[name=" + selectorID + "]:checked").val() == null) {
                setFieldErrorSpan(selectorID, invalidMessage, true);
            }
            else {
                setFieldErrorSpan(selectorID, "", false);
                field_valid = true;
            }
            break;

    }

    return field_valid;

}

setFieldErrorSpan = function(selectorID, message, show) {
    $("#" + selectorID + "-err").html(message);
    if (show) {
        $("#" + selectorID + "-err").show();
    }
    else {
        $("#" + selectorID + "-err").hide();
    }

}

resetAllErrors = function() {
    $("span.error").each(function() { $(this).hide(); });
}

resetAllFields = function(containerID) {
    $("#" + containerID + " :input[type=text]").each(function() { $(this).val(""); });
    $("#" + containerID + " select").each(function() { $(this).val("invalid"); });
    $("#" + containerID + " :input[type=radio]").each(function() { $(this).attr("checked", false); });
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toUTCString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

loadIE6Prompt = function() {


    if ($.browser.msie && $.browser.version == "6.0") {
    var ieCookieCheck = getCookie('ie6prompt');

   
    
    if (ieCookieCheck == null) {

        $("#viewport-IE6-wrapper").show();

        $(document).ready(function() {
            adjustViewport();
        });

        $(window).resize(function() {
            adjustViewport();
        });

        $("#ignore-prompt").click(function() {
            setCookie('ie6prompt', 'displayed', 30);
            setCookie('ie6prompt_small', 'displayed', 1);
            $("#viewport-IE6-wrapper").hide();
        });

    }

    if (ieCookieCheck == "") {

        $("#viewport-IE6-wrapper").show();

        $(document).ready(function() {
            adjustViewport();
        });

        $(window).resize(function() {
            adjustViewport();
        });

        $("#ignore-prompt").click(function() {
            setCookie('ie6prompt', 'displayed', 30);
            setCookie('ie6prompt_small', 'displayed', 1);
            $("#viewport-IE6-wrapper").hide();
        });

    }
    }
}

adjustViewport = function() {
    var width = $(document).width();
    var height = $(document).height();

    $("#viewport-IE6-wrapper").css("height", height);
    $("#viewport-IE6-wrapper").css("width", width);
}

loadIE6Prompt();
