/******************************************************************************
* cmJQuery.js
*******************************************************************************

*******************************************************************************
*                                                                             *
* Copyright 2010									                          *
*                                                                             *
******************************************************************************/
function cmDialogOpenIframe(dialog, url, width, height, closeTitle, args) {
    cmDialogOpen(dialog, width, height, closeTitle, args);
    var varIframeScrolling = "no";
    if (args != null) {
        if (args["iframe_scrolling"] != null) varIframeScrolling = args["iframe_scrolling"];
    }
    $(dialog).html("<iframe src=\"" + url + "\" width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"" + varIframeScrolling + "\"></iframe>");
}

function cmDialogOpen(dialog, width, height, closeTitle, args) {
    var varModal = true;
    var varAutoOpen = false;
    var varResizable = false;
    var varDraggable = false;

    if (args != null) {
        if (args["modal"] != null) varModal = args["modal"];
        if (args["autoOpen"] != null) varAutoOpen = args["autoOpen"];
        if (args["resizable"] != null) varResizable = args["resizable"];
        if (args["draggable"] != null) varDraggable = args["draggable"];
    }
    
    $(dialog).dialog(
    {
        modal: varModal,
        autoOpen: varAutoOpen,
        resizable: varResizable,
        draggable: varDraggable
    });

    if (width != null) cmDialogSetProperty(dialog, 'width', width);
    if (height != null) cmDialogSetProperty(dialog, 'height', height);

    if ((closeTitle != null) && (closeTitle != '')) cmDialogSetProperty(dialog, "closeText", closeTitle);
    if (closeTitle != null && closeTitle == '') {
        $(dialog).dialog({
            open: function(event, ui) {
                $(this).parent().children().children('.ui-dialog-titlebar-close').hide();
            }
        })
    }
    else cmDialogSetProperty(dialog, "closeText", objThesaurus.translate("ebpInter50"));

    $(dialog).dialog("open");
    
    $(document).scroll(function() {
        $(dialog).dialog("option", "position", "center");
    });
}

function cmDialogClose(dialog) {
    $(dialog).dialog("close");
}

function cmDialogRegisterCloseAction(dialog, closeAction) {
    $(dialog).bind("dialogclose", closeAction);
}

function cmDialogSetProperty(dialog, option, value) {
   $(dialog).dialog("option", option, value);
}

function cmDialogHideCloseButton(dialog) {
    $(dialog).parent().children().children('.ui-dialog-titlebar-close').hide();
}

function cmDialogShowCloseButton(dialog) {
    $(dialog).parent().children().children('.ui-dialog-titlebar-close').show();
    cmDialogSetProperty(dialog, "closeText", objThesaurus.translate("ebpInter50"));
}

function cmDialogGetProperty(dialog, option) {
    return $(dialog).dialog("option", option);
}

function cmDialogRedirection(dialog, url) {
    $(dialog).dialog("destroy");
    window.location = url;
}

function cmDialogResize(dialog, pattern, margin) {
    if (margin == null) margin = 0;
    var value = (cmDialogGetProperty(dialog, "height") - $(pattern).height()) + cmDialogGetProperty(dialog, "height") + margin + 30;
    cmDialogSetProperty(dialog, "height", value);
    cmDialogSetProperty(dialog, "position", "center");
}

function cmDialogResizeIframe(dialog, iframe, pattern, margin){
	if(margin == null) margin = 0;
	cmDialogSetProperty(dialog, "height", $(pattern, $(iframe, dialog).contents()).height() + margin);
	cmDialogSetProperty(dialog, "position", "center");
}

function cmDialogResizeIframeOpen(margin) {
    $(".ui-dialog-content").each(function() {
        if ($(this).dialog("isOpen")) cmDialogResizeIframe("#" + $(this).attr('id'), "iframe", "body", margin);
    });
}

function cmShowMessage(container, msg, url, hide, duration) {
    $(container).html("<ul>" + msg + "</ul>").show("fast", function() {
        if (hide == null || hide == true) setTimeout("cmHideMessage(\"" + container + "\", \"" + url + "\");", ((duration == null) ? 5000 : duration));
    });
}

function cmHideMessage(container, url) {
    $(container).hide("fast", function() {
        $(container).html("");
        if (url != null && url != "undefined") {
            window.location.href = url;
        }
    });
}

function cmAuthentificationDeleteParams() {
    var urlRedirect = (window.location.href.indexOf('#') == -1) ? window.location.href : window.location.href.substring(0, window.location.href.indexOf('#'));

    if (urlRedirect.indexOf("?") != -1) {
        var tabQuery = new Array();
        var params = urlRedirect.substring(urlRedirect.indexOf("?") + 1);
        var tabParams = params.split("&");
        for (var i = 0; i < tabParams.length; i++) {
            var tabParam = tabParams[i].split("=");
            if ((tabParam[0] != "formId") && (tabParam[0] != "step")) tabQuery[tabQuery.length] = tabParams[i];
        }
        urlRedirect = urlRedirect.substring(0, urlRedirect.indexOf("?") + 1);
        for (var i = 0; i < tabQuery.length; i++) urlRedirect += tabQuery[i] + "&";
        if (urlRedirect.substring(urlRedirect.length - 1) == "&") urlRedirect = urlRedirect.substring(0, urlRedirect.length - 1);
    }

    return urlRedirect;
}

(function($) {

    $.fn.select_autocomplete = function(inputText, options) {

        // make sure we have an options object
        options = options || {};

        // setup our defaults
        var defaults = {
            minChars: 0
		    , width: 430
		    , matchContains: true
		    , autoFill: false
		    , formatItem: function(row, i, max) {
		        return row.name;
		    }
		    , formatMatch: function(row, i, max) {
		        return row.name;
		    }
		    , formatResult: function(row) {
		        return row.name;
		    }
        };

        options = $.extend(defaults, options);

        return this.each(function() {

            //stick each of it's options in to an items array of objects with name and value attributes 
            var $this = $(this),
			    data = [],
			    $input = (inputText != null && inputText != "") ? $(inputText) : $('<input type="text" />');

            if (this.tagName.toLowerCase() != 'select') { return; }


            $this.children('option').each(function() {

                var $option = $(this);

                if ($option.val() != '') { //ignore empty value options

                    data.push({
                        name: $option.html()
					    , value: $option.val()
                    });
                }
            });

            // insert the input after the select
            if (inputText == null || inputText == "") $this.after($input);

            // add it our data
            options.data = data;

            //make the input box into an autocomplete for the select items
            $input.autocomplete(data, options);

            //make the result handler set the selected item in the select list
            $input.result(function(event, selected_item, formatted) {
                $($this.find('option[value=' + selected_item.value + ']')[0]).attr('selected', true);
                $this.change();
            });

            $input.blur(function() {
                // autocomplete has removed blank options
                // ensure that if value is removed we select the blank option if available
                if (this.value == "") {
                    $($this.find('option[value=]')[0]).attr('selected', true);
                }

                /*   failsafe to ensure text box always represents the value being used in the select
                *   there are edge cases where if you leave the field part way through the word, or clear the value when no blank option is available
                *   that force a mismatch between the 2 elements
                */
                if (this.value != $this[0].options[$this[0].selectedIndex].text) {
                    $input.val($this[0].options[$this[0].selectedIndex].text);
                }
            });

            //set the initial text value of the autocomplete input box to the text node of the selected item in the select control
            $input.val($this[0].options[$this[0].selectedIndex].text);

            //normally, you'd hide the select list but we won't for this demo
            $this.hide();
        });
    };

})(jQuery);

function stopEvents(e) {
    $("a[href^='javascript:__doPostBack']").unbind('click', stopEvents);
    $("a[href^='javascript:__doPostBack']").click(function(e2) {
        e2.preventDefault();
        e2.stopPropagation();
        return false;
    });
}

function addGoogleAnalyticsDownloadTracking(){
    $("a[href$='.pdf'], a[href$='.doc'], a[href$='.docx'], a[href$='.xls'], a[href$='.xlsx']").click(function(){
	    var href = $(this).attr('href');
	    gaRuntime.trackEvent(href.substr(href.lastIndexOf(".") + 1).toUpperCase(), 'Download', href);
	    //gaq.push(['_trackEvent', href.substr(href.lastIndexOf(".") + 1).toUpperCase(), 'Download', href]);
    });
}

function getUrlParam(url, name)
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec(url);
    if(results == null)
        return "";
    else
        return results[1];
}

$(document).ready(function() 
{    	
	$('.cmMenuBar > li > ul').masonry({
        columnWidth: 193 
    });
	
    $('.cmMenuBar > li > ul').css('visibility', 'visible');
    $('.cmMenuBar > li > ul ul').css('visibility', 'visible');
    $('.cmMenuBar > li > ul').css('display', 'none');
    
    $('.cmMenuBar > li').mouseenter(function(){
        var li = $(this);
        li.addClass('selected');
        var previousLi = getPreviousLi(li);
        if(previousLi != null && li.children("ul").length > 0) previousLi.addClass('backgroundImageNone');
        var ul = $("ul:first", li);
        ul.css("margin-left", 0);
        var windowWidth = $(document).width();
        var liLeft = $(li).position().left;
        var ulWidth = $(ul).width();

        if(liLeft + ulWidth > windowWidth)
            ul.css("margin-left", Math.round((windowWidth -(liLeft + ulWidth))));
        
        ul.fadeIn();
    });

    $('.cmMenuBar > li').mouseleave(function(){
        var li = $(this);
        li.removeClass('selected');
        var previousLi = getPreviousLi(li);
        if(previousLi != null && li.children("ul").length > 0) previousLi.removeClass('backgroundImageNone');  
        var ul = $("ul:first", li);
        ul.fadeOut();
    });
    
    function getPreviousLi(li){
        var parentUl = li.parent();
        var index = parentUl.children().index(li);
        if(index > 0){
            var previousLi = parentUl.children().eq(index-1);
            return previousLi;
        }
        return null;
    }
    
   	if ($('ul.cmAuthentication ul.cmShortcutAccount > li').length > 0) {
   	    $('ul.cmAuthentication').superfish(
   	    { 
            delay:       1000,                            // one second delay on mouseout 
            animation:   {opacity:'show'},                // fade-in and slide-down animation 
            speed:       'slow',                          // faster animation speed 
            autoArrows:  false,                           // disable generation of arrow mark-up 
            dropShadows: false                            // disable drop shadows 
        });
    }
    
    $('ul.cmShortcutLang').superfish(
   	{ 
        delay:       1000,                            // one second delay on mouseout 
        animation:   {opacity:'show'},                // fade-in and slide-down animation 
        speed:       'slow',                          // faster animation speed 
        autoArrows:  false,                           // disable generation of arrow mark-up 
        dropShadows: false                            // disable drop shadows 
    });
    
     $('.cmMenuLeft ul ul').superfish(
   	{ 
        delay:       1000,                            // one second delay on mouseout 
        animation:   {opacity:'show'},                // fade-in and slide-down animation 
        speed:       'slow',                          // faster animation speed 
        autoArrows:  false,                           // disable generation of arrow mark-up 
        dropShadows: false                            // disable drop shadows 
    });
    
    $('.cmMenuLeftExcep ul ul').superfish(
   	{ 
        delay:       1000,                            // one second delay on mouseout 
        animation:   {opacity:'show'},                // fade-in and slide-down animation 
        speed:       'slow',                          // faster animation speed 
        autoArrows:  false,                           // disable generation of arrow mark-up 
        dropShadows: false                            // disable drop shadows 
    });
    
    $('#cmSiteMap > li > ul').equalHeights(); 
    
    $(".cmStandardTabs ul li a").prepend("<span></span>");
    
    $(".cmStandardTabs").tabs();
	
	$("input[type=checkbox], input[type=radio], input[type=file]").uniform();
	$("select:not(.richTextButtonBar select)").uniform();
		
	$('.cmToolTip').tipTip(	
	{
		defaultPosition:'right',
		maxWidth:'202px'
	});
	//$("a[href^='javascript:__doPostBack']").click(stopEvents);
	$("a[href^='javascript:__doPostBack']:not([class~='usePostback'])").click(stopEvents);
	
	addGoogleAnalyticsDownloadTracking();
});
