/** 
 * Google Analytics
 */
$.fn.decHTML = function(){
    return this.each(function(){
        var me = $(this);
        var html = me.html();
        me.html(html.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>'));
    });
};

/* Ensure language code is in the format aa-AA. */
normaliseLang = function(lang){
    lang = lang.replace(/_/, '-').toLowerCase();
    if (lang.length > 3) {
        lang = lang.substring(0, 3) + lang.substring(3).toUpperCase();
    }
    return lang;
}

/* Retrieve the default language set for the browser. */
defaultLanguage = normaliseLang(navigator.language /* Mozilla */ || navigator.userLanguage /* IE */);

// if your default langugage is not english
if (defaultLanguage.substring(0, 2) != 'en') {
    $.ajax({
        url: '/remote/RemoteLanguageService.cfc?method=getBrowserLanguage&returnFormat=json&languageKey=' + defaultLanguage.substring(0, 2),
        dataType: 'json',
        success: function(data){
            //populate the popup with the data returned from the service        
            $.fn.colorbox({
                html: '<div id="welcome_wrapper">' + data + '</div>',
                width: "862",
                height: "522"
            })
            
        }
    });
}

$.exists = function(selector){
    return ($(selector).length > 0);
}

closeEmailPopUp = function(elm){
    var popUp_draw_right = $(elm).parents('#email_popup_draw_right').fadeOut(200);
    var popUp = $(elm).parents('#email_popup').fadeOut(200);
    var popUp_mapArrow = $(elm).parents('div').fadeOut(150);
    return false;
}

validateContactForm = function(form){
    $(form).validate({
        rules: {
            email_address: {
                required: true,
                email: true
            },
            email_message: {
                required: true
            }
        }
    });
    return $(form).valid();
}



//URI around the world google map function 

if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
}
else 
    if (document.all) { // Internet Explorer
        document.onmousemove = captureMousePosition;
    }
    else 
        if (document.getElementById) { // Netcsape 6
            document.onmousemove = captureMousePosition;
        }
// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page
function captureMousePosition(e){
    if (document.layers) {
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth + window.pageXOffset;
        yMousePosMax = window.innerHeight + window.pageYOffset;
    }
    else 
        if (document.all) {
            xMousePos = window.event.x + document.body.scrollLeft;
            yMousePos = window.event.y + document.body.scrollTop;
            xMousePosMax = document.body.clientWidth + document.body.scrollLeft;
            yMousePosMax = document.body.clientHeight + document.body.scrollTop;
        }
        else 
            if (document.getElementById) {
                xMousePos = e.pageX;
                yMousePos = e.pageY;
                xMousePosMax = window.innerWidth + window.pageXOffset;
                yMousePosMax = window.innerHeight + window.pageYOffset;
            }
}

function getNodeCDATA(element){
    var ie = (typeof window.ActiveXObject != 'undefined');
    var returnText;
    
    if (ie) {
    
        if (element.hasChildNodes) {
            returnText = element.childNodes[0].nodeValue;
        }
    }
    else {
    
        if (element.hasChildNodes) {
            returnText = element.childNodes[1].nodeValue;
        }
        
        
    }
    
    return returnText;
}




//URI around the world google map function 
function initializeURIGMap(){
    if (GBrowserIsCompatible()) {
    
        var map = new GMap2(document.getElementById("map_canvas"));
        //add controls
        //map.addControl(new GSmallMapControl());
        //add zoom buttons and slider
        map.addControl(new GLargeMapControl());
        //add control for map type
        map.addControl(new GMapTypeControl());
        //define map types available
        map.addMapType(G_NORMAL_MAP);
        map.addMapType(G_SATELLITE_MAP);
        map.addMapType(G_PHYSICAL_MAP);
        map.removeMapType(G_HYBRID_MAP);
        
        var minZoom = 2;
        var maxZoom = 14;
        var opts = {
            minResolution: minZoom,
            maxResolution: maxZoom
        };
        
        // ugly hack to restrict the map control to use approrpiate zoom levels only
        GMapType.prototype.getMinimumResolution = function(latlng){
            return 2;
        }
        GMapType.prototype.getMaximumResolution = function(latlng){
            return 14;
        }
        
        var limitedZoomMapType = new GMapType(G_PHYSICAL_MAP.getTileLayers(), G_PHYSICAL_MAP.getProjection(), "SATELLITE", opts);
        map.setMapType(limitedZoomMapType)
        
        ///set center
        map.setCenter(new GLatLng(25.71859, 6.679688), 2);
        
        bubble_left = new EBubble(map, "/images/maps/bubble_background_left.png", new GSize(324, 360), new GSize(230, 200), new GPoint(16, 30), new GPoint(315, 80));
        bubble_right = new EBubble(map, "/images/maps/bubble_background_right.png", new GSize(324, 360), new GSize(230, 200), new GPoint(60, 30), new GPoint(-5, 80));
        
        var MyIcon = new GIcon(); // create a new Google Icon object
        MyIcon.image = "/images/icons/map_marker.png";// image file name
        MyIcon.iconSize = new GSize(22, 24);// width (px) and height (px)
        MyIcon.shadowSize = new GSize(35, 45);// the shadow's size
        MyIcon.iconAnchor = new GPoint(0, 24);// base of the icon
        MyIcon.infoWindowAnchor = new GPoint(0, 0);// info window ba  
        // A function to create the marker and set up the event window 
        function createMarker(point, thisHtml, MyIcon){
            //set up custom marker           
            var marker = new GMarker(point, MyIcon);
            GEvent.addListener(marker, "click", function(){
                if (xMousePos >= xMousePosMax / 2) {
                    bubble_left.openOnMarker(marker, thisHtml);
                    bubble_right.hide();
                }
                else {
                    bubble_right.openOnMarker(marker, thisHtml);
                    bubble_left.hide();
                }
            });
            return marker;
        }
        
        // Read the data from example.xml
        GDownloadUrl("/files/world_of_uri/data.xml", function(doc){
            var xmlDoc = GXml.parse(doc);
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");
            
            for (var i = 0; i < markers.length; i++) {
            
                var name = xmlDoc.documentElement.getElementsByTagName("name");
                var purpose = xmlDoc.documentElement.getElementsByTagName("purpose");
                var more = xmlDoc.documentElement.getElementsByTagName("more");
                
                // obtain the attribues of each marker
                var lat = parseFloat(markers[i].getAttribute("lat"));
                var lng = parseFloat(markers[i].getAttribute("lng"));
                var point = new GLatLng(lat, lng);
                try {
                    var thisName = name[i].childNodes[0].nodeValue;
                } 
                catch (e) {
                    var thisName = '';
                }
                try {
										var thisPurpose = getNodeCDATA(purpose[i]);
                    
                } 
                catch (e) {
									  try{
											var thisPurpose = purpose[i].childNodes[0].nodeValue;
										}catch (e){
											var thisPurpose = '';
										}
                }
                try {
                    var thisMore = getNodeCDATA(more[i]);
                } 
                catch (e) {
                    var thisMore = '';
                }
								
                // create HTML in marker
                var thisHtml = '<div id="bubble_wrapper">' + '<span id="bubble">' + '<a href="##" onclick="return closeEmailPopUp(this)"><img alt="Button: Close email" id="close_email_popup" class="map" src="/images/staff_email/email_close_button.gif" style="float:right !important;"></a>' + '<h2>' + thisName + '</h2>' + '<p>' + thisPurpose + '</p>' + '<h3>' + thisMore + '</h3>' + '</span>' + '</div>';
                // create the marker object
                var marker = createMarker(point, thisHtml, MyIcon);
                map.addOverlay(marker);
            }
        });//End GDownloadUrl method
        // Add a move listener to restrict the bounds range
        GEvent.addListener(map, "move", function(){
            checkBounds();
        });
        
        // The allowed region which the whole map must be within
        var allowedBounds = new GLatLngBounds(new GLatLng(-60, 10), new GLatLng(60, -10));
        
        // If the map position is out of range, move it back
        function checkBounds(){
            // Perform the check and return if OK
            if (allowedBounds.contains(map.getCenter())) {
                return;
            }
            // It`s not OK, so find the nearest allowed point and move there
            var C = map.getCenter();
            var X = C.lng();
            var Y = C.lat();
            
            var AmaxX = allowedBounds.getNorthEast().lng();
            var AmaxY = allowedBounds.getNorthEast().lat();
            var AminX = allowedBounds.getSouthWest().lng();
            var AminY = allowedBounds.getSouthWest().lat();
            
            if (X < AminX) {
                X = AminX;
            }
            if (X > AmaxX) {
                X = AmaxX;
            }
            if (Y < AminY) {
                Y = AminY;
            }
            if (Y > AmaxY) {
                Y = AmaxY;
            }
            //alert ("Restricting "+Y+" "+X);
            map.setCenter(new GLatLng(Y, X));
        }
    }
    else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
};//End initializeURIGMap()

$(document).ready(function(){

    /**
     IE 6 PNG fix
     if (ie6BadBrowser) {
     $('.mapContainer, .mapInteractions, .hovers, .hovers a, .hovers a span, ##africa, ##africa span, ##africa:hover, ##CC_region_country_wrapper ##africa span, ##CC_region_country_wrapper a##africa:hover div, ##asia, ##asia span, ##asia:hover, ##CC_region_country_wrapper, ##asia span, ##CC_region_country_wrapper a##asia:hover div, ##europe, ##europe span, ##europe:hover, ##CC_region_country_wrapper ##europe span, ##CC_region_country_wrapper a##europe:hover div, ##middleeast, ##middleeast span, ##middleeast:hover, ##CC_region_country_wrapper, ##middleeast span, ##CC_region_country_wrapper a##middleeast:hover div, ##namerica, ##namerica span, ##namerica:hover, ##CC_region_country_wrapper ##namerica span, ##CC_region_country_wrapper a##namerica:hover div, ##samerica, ##samerica span, ##samerica:hover, ##CC_region_country_wrapper ##samerica span, ##CC_region_country_wrapper a##samerica:hover div, ##seasia, ##seasia span, ##seasia:hover, ##CC_region_country_wrapper ##seasia span, ##CC_region_country_wrapper a##seasia:hover div, ##textBubble, ##textBubble p, ##textBubble p a, ##textBubble p a.linkout, ##textBubble p a.linkout:hover, ##textBubble.africa, ##textBubble.asia, ##textBubble.europe, ##textBubble.middleeast, ##textBubble.namerica, ##textBubble.samerica, ##textBubble.seasia').ifixpng();
     }*/
    /**
     * script to align the heights of the sidebar with the intro div. Calculates the total heights
     * of both div boxes to ensure that they always line-up
     */
    if ($.exists('#subpage_col2_header_directory') && $.exists('#subpage_col3_wrapper_directory')) {
    
        var col2Header = $('#subpage_col2_header_directory').height();
        var col3Header = $('#subpage_col3_header_directory').height();
        var col3Sidebar = $('#subpage_col3_wrapper_directory').height();
        var sideBarHeight = parseInt(col3Sidebar) + 40;
        
        /**
         if there is a sidebar as well, add that in
         */
        if ($.exists('#subpage_col3_header_directory')) {
            sideBarHeight += parseInt(col3Header) + 10;
        }
        
        /**
         * apply the height fix to either the main content or the sidebar appropriately
         */
        if (col2Header > sideBarHeight) {
            $('#subpage_col3_wrapper_directory').css('height', $('#subpage_col3_wrapper_directory').height() + (col2Header - sideBarHeight));
        }
    }
    
    
    /**
     * script to align the heights of the home three column layout below the banner. Calculates the total heights
     * of both div boxes to ensure that they always line-up
     */
    if ($.exists('#home #col1 #col1_content') && $.exists('#home #col3 #col3_content') && $.exists('#home #col2 #col2_content')) {
    
        var col1Header = $('#home #col1 #col1_content').height();
        var col2Header = $('#home #col2 #col2_content').height();
        var col3Header = $('#home #col3 #col3_content').height();
        /*apply the height fix to either the main content or the sidebar appropriately*/
        if ((col3Header > col1Header) && (col3Header > col2Header)) {
            $('#home #col1 #col1_content').css('height', col3Header);
            $('#home #col2 #col2_content').css('height', col3Header);
            $('#home #col3 #col3_content').css('height', col3Header);
        }
        else 
            if ((col2Header > col1Header) && (col2Header > col3Header)) {
                $('#home #col1 #col1_content').css('height', col2Header);
                $('#home #col2 #col2_content').css('height', col2Header);
                $('#home #col3 #col3_content').css('height', col2Header);
            }
            else 
                if ((col1Header > col3Header) && (col1Header > col2Header)) {
                    $('#home #col1 #col1_content').css('height', col1Header);
                    $('#home #col2 #col2_content').css('height', col1Header);
                    $('#home #col3 #col3_content').css('height', col1Header);
                }
        
    }
    
    /**
     Clears the search box
     */
    $("#search").click(function(){
        if ($("#search").size() >= 1) {
            $("#search").val('');
        }
    });
    
    $("input.gsc-input").click(function(){
        if ($("input.gsc-input").size() >= 1) {
            $("input.gsc-input").val('');
        }
    });
    
    
    
    /**
     * Superfish Menu
     */
    $(function(){
        $('ul.sf-menu').superfish();
    });
    
    /** 
     * Coda Slider
     */
    if ($.exists("div#slider1")) {
        $(window).bind("load", function(){
            $("div#slider1").codaSlider({
                crossLinking: false,
                dynamicArrows: false
            });
        });
    }
    
    /**
     * Drop down Signin Box
     */
    $("#signin_wrapper").stop().fadeTo(150, 0.01);
    $("#signin_bubble_tip").stop().fadeTo(150, 0.01);
    $("#signin_link").click(function(){
        $("#signin_wrapper").stop().fadeTo(150, 1);
        $("#signin_bubble_tip").stop().fadeTo(150, 1).css('visibility', 'visible');
        $("#signin").stop().fadeTo(150, 1).css('visibility', 'visible');
        $("#close_signin").stop().fadeTo(150, 1).css('visibility', 'visible');
        return false;
    });
    $("#close_signin").click(function(){
        $("#signin_wrapper").stop().fadeTo(150, 0.01);
        $("#signin").stop().fadeTo(150, 0.01);
        $("#signin_bubble_tip").stop().fadeTo(150, 0.01);
        return false;
    });
    
    /**
     * read more expand/collapse (used in action areas)
     */
    $(".readmore").truncate(400, {
        chars: /\s/,
        trail: [" (<a href='#' class='truncate_show'>Read More</a>...)", " (<a href='#' class='truncate_hide'>Collapse</a>... )"]
    });
    
    
    /**
     * Example of preserving a JavaScript event for inline calls.
     */
    $("#click").click(function(){
        $('#click').css({
            "background-color": "#f00",
            "color": "#fff",
            "cursor": "inherit"
        }).text("Open this window again and this message will still be here.");
        return false;
    });
    
    /**
     * This script draws the email contact pop up box with the arrow pointing left to the trigger link
     */
    $(".email_link").bind("click", function(e){
        var email_link = ($(this))
        var emailRel = $(this).attr('rel');
        emailRel = emailRel.split('|');
        var emailAddress = escape(emailRel[0]);
        var emailSubject = escape(emailRel[1]);
        var popupTitle = escape(emailRel[2]);
        
        if (emailRel.length <= 2) {
            popupTitle = "";
        }
        
        $('#email_popup').load('/views/uri/staff_email.cfm?email=' + emailAddress + '&emailSubject=' + emailSubject + '&popupTitle=' + popupTitle);
        var emailLinkWidth = $("a.email_link").width();
        $("#email_popup").css({
            left: email_link.offset().left + (emailLinkWidth + 4),
            top: email_link.offset().top - 75
        }).fadeIn(200);
    });
    
    /**
     * This script draws the email contact pop up box with the arrow pointing right to the trigger link
     */
    $(".email_link_draw_right").bind("click", function(e){
        var email_link = ($(this))
        var emailRel = $(this).attr('rel');
        emailRel = emailRel.split('|');
        var emailAddress = escape(emailRel[0]);
        var emailSubject = escape(emailRel[1]);
        var popupTitle = escape(emailRel[2]);
        
        if (emailRel.length <= 2) {
            popupTitle = "";
        }
        
        $('#email_popup_draw_right').load('/views/uri/staff_email.cfm?email=' + emailAddress + '&emailSubject=' + emailSubject + '&popupTitle=' + popupTitle);
        var emailLinkWidth = $("a.email_link_draw_right").width();
        $("#email_popup_draw_right").css({
            left: email_link.offset().left - (emailLinkWidth + 365),
            top: email_link.offset().top - 82
        }).fadeIn(200);
    });
    
    /** 
     * script for tabbed content on the action area and program detail pages
     *
     */
    $('.tabbedContentAction li a').bind('click', function(e){
        var tabbedContentAction = $(this);
        //remove selected from all li's
        tabbedContentAction.parent().siblings().removeClass('selected');
        //select this li
        tabbedContentAction.parent().addClass('selected');
        //hide all tab content
        $('#tabbedContent').children().hide();
        //show this tab content
        $('#' + tabbedContentAction.attr('rel')).show();
        //abort execution of link
        return false;
    });
    
    /**
     * Validate Calls
     */
    if ($('#Join_CC').length > 0) {
        $("#Join_CC").validate();
    }
    
    
    /**
     * Draw the uri around the world gmap if necessary
     */
    if ($('#map_canvas').length) {
        initializeURIGMap();
    }
    
    
    
    $('textarea.tinymce').tinymce({
        // Location of TinyMCE script
        script_url: '/js/tiny_mce/tiny_mce.js',
        mode: "none",
        theme: "advanced",
        plugins: "table,advimage,advlink,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,xhtmlxtras",
        valid_elements: "*[*]",
        theme_advanced_toolbar_location: "top",
        
        theme_advanced_buttons1: "bold,italic,underline,strikethrough,separator",
        theme_advanced_buttons1_add: "justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,formatselect,styleselect,fontsizeselect",
        
        theme_advanced_buttons2_add_before: "cut,copy,paste,pastetext,pasteword,separator,search,replace,separator",
        theme_advanced_buttons2: "undo,redo,separator,link,unlink,anchor,image,media,separator,forecolor,backcolor,separator,hr",
        
        theme_advanced_buttons3: "tablecontrols,separator",
        theme_advanced_buttons3_add: "code",
        
        theme_advanced_resize_horizontal: false,
        theme_advanced_resizing: true,
        
        
        relative_urls: false,
        convert_urls: true,
        verify_html: false,
        auto_reset_designmode: true,
        theme_advanced_blockformats: "p,address,pre,h1,h2,h3,h4,h5,h6,div",
        
        
        // Example content CSS (should be your site CSS)
        content_css: "/css/screen/content.css"
    
    });
    
    
    
}); //End Document Ready
$(window).load(function(){
    /**
     * script to align the heights of the sidebar with the intro div. Calculates the total heights
     * of both div boxes to ensure that they always line-up
     */
    if ($.exists('#subpage_col2_header_directory') && $.exists('#subpage_col3_wrapper_directory')) {
    
        var col2Header = $('#subpage_col2_header_directory').height();
        var col3Header = $('#subpage_col3_header_directory').height();
        var col3Sidebar = $('#subpage_col3_wrapper_directory').height();
        var sideBarHeight = parseInt(col3Sidebar) + 40;
        
        /**
         if there is a sidebar as well, add that in
         */
        if ($.exists('#subpage_col3_header_directory')) {
            sideBarHeight += parseInt(col3Header) + 10;
        }
        
        /**
         * apply the height fix to either the main content or the sidebar appropriately
         */
        if (col2Header >= sideBarHeight) {
            $('#subpage_col3_wrapper_directory').css('height', $('#subpage_col3_wrapper_directory').height() + 30 + (col2Header - sideBarHeight));
            $('#subpage_col2_header_directory').css('height', $('#subpage_col2_header_directory').height() + 30);
            
        }
        else 
            if (sideBarHeight > col2Header) {
                $('#subpage_col2_header_directory').css('height', $('#subpage_col2_header_directory').height() + (sideBarHeight - col2Header));
            }
    }
    
});
