﻿/* NOTIFICATIONS */

var notificationTypes = {
    SUCCESS : "success",
    ERROR : "error"
}
function CallAJAXPost(){

	var successFN = CallAJAXPost.arguments[CallAJAXPost.arguments.length-2];
	var errorFN = CallAJAXPost.arguments[CallAJAXPost.arguments.length-1];
	var baseURL = $('#hfBaseURL').attr("value");
	var url = baseURL + CallAJAXPost.arguments[0];
	var params = CallAJAXPost.arguments[1];
	
	$.ajax({
	  type: "POST",
	  url: url,
	  data: $.toJSON(params),
	  contentType: "application/json; charset=utf-8",
	  dataType: "json",
	  success: function(msg) {
		successFN(msg.d);
	  },
	  error: function(msg) {
		errorFN(msg);
		showNotification($("#hfDefaultErrorMessage").val(), notificationTypes.ERROR)
	  }
	});
}
function showNotification(message, type) {
    $(document).ready(function () {
        // get existing popup dom element and remove it from dom
        var notificationPopup = $("#notificationPopup");
        if (notificationPopup.length) {
            notificationPopup = notificationPopup.remove();
        }
        // create new popup dom element
        notificationPopup =
        $("<div id='notificationPopup'>" +
            "<span id='notificationPopup-message'></span>" +
            "</div>");
        notificationPopup.appendTo("#content");
        //set message
        notificationPopup.find("#notificationPopup-message").html(message);
        // clear notification types from class attr
        notificationPopup.removeClass(notificationTypes.INFO);
        notificationPopup.removeClass(notificationTypes.ERROR);
        // add notification type class
        notificationPopup.addClass(type);
        // show and hide after a few seconds
        notificationPopup.fadeIn(1000).delay(7000).fadeOut(500);
    });
}

function SetStyleInCheckAndRadioButtons() {
    $("#take-exam input[type='checkbox']").custCheckBox();
    //$("#take-exam input[type='radio']").custCheckBox();
}

function SelectMessage(divMessage) {
    if ($(divMessage).is(".closed-message")) {
        $(divMessage).removeClass("closed-message");
        $(divMessage).addClass("opened-message");
    }
    else {
        $(divMessage).removeClass("opened-message");
        $(divMessage).addClass("closed-message");
    }
}
function HighlightMessage(divMessage) {
    $(divMessage).addClass("highlight");
}
function UnHighlightMessage(divMessage) {
    $(divMessage).removeClass("highlight");
}

function HighlightSearchResult(divMessage) {
    $(divMessage).addClass("highlight");
}
function UnHighlightSearchResult(divMessage) {
    $(divMessage).removeClass("highlight");
}

function ShowControlById(id) {
    $('[id$="' + id + '"]').fadeIn(300);
}

function HideControlById(id) {
    $('[id$="' + id + '"]').hide();
}

$(document).ready(function () {

    SetStyleInCheckAndRadioButtons();

    // selectboxes
    initSelectboxes();

    $("#iframeProgress").css({
        "opacity": "0.0"
    });
    $("#backgroundProgress").css({
        "opacity": "0.7"
    });

    $('*[istab]').click(function () {
        effectTabs(this);
    });


    DefaultButtonExtendedTextBox();
    $('body').click(function (event) {

        if ($(event.target).is('.cancelButton')) {
            link = $(event.target).attr("idTarget");
            if (link) {
                $("#" + link).attr("showConfirmationPopUp", "true");

                classPopUp = $("#" + link).attr("popUpConfirm");
                disablePopup($("." + classPopUp));
            }
        }

        if ($(event.target).is('.popupCountriesTrigger')) {
            showPopupCountries("popUpCountries");
        }
		
        if ($(event.target).is('.popupBookmarksTrigger')) {
            showPopupBookmarks("popUpBookmarks");
        }

        //Click the x event!
        if ($(event.target).is('.popUpCloseInvitation')) {
            disablePopupInvitation($(".popUpInvitation"));
        }

        if ($(event.target).is('.triggerShare')) {
            showPopup("popUpShare");
        }
        //Click the x event!
        if ($(event.target).is('.popUpCloseShare')) {
            disablePopup($(".popUpShare"));
        }

        if ($(event.target).is('.popUpCloseShareMail')) {
            disablePopup($(".popUpShareByMail"));
        }


        if ($(event.target).is('.popUpCloseSchedule')) {
            disablePopup($(".popUpSchedule"));
        }

        if ($(event.target).is('.triggerSubscribeToTeam')) {
            showPopup("popUpSubscribeToTeam");
        }

        //Click the x event!
        if ($(event.target).is('.popUpCloseSubscribeToTeam')) {
            disablePopup($(".popUpSubscribeToTeam"));
        }

        //Click the x event!
        if ($(event.target).is('.popUpCloseMessageTakeExam')) {
            disablePopup($(".popUpMessageTakeExam"));
        }

        //Click the x event!
        if ($(event.target).is('.popUpCloseCountries')) {
            disablePopupCountries($(".popUpCountries"));
        }
		
		//Click the x event!
        if ($(event.target).is('.popUpCloseBookmarks')) {
            disablePopupCountries($(".popUpBookmarks"));
        }
		
		
    });

	BindCustomCheckBox();
	
    wrapText();

    SetStyleTags();
	
	$('#mycarousel').jcarousel();
});

function BindCustomCheckBox()
{
	$("#answer_container .cust_checkbox.checkbox").click(function()
	{
		$("#msgRequiredAnswer").css({ visibility: "hidden" });
	});
}

function showPopupSubscribeCT(cssClass, idEducationTypeSelected,idContentType){
	$('input[id$="hfCTClick"]').val(idContentType);
	$('input[id$="hfExamClick"]').val(0);
	showPopupSubscribe(cssClass, idEducationTypeSelected);
}

function showPopupSubscribeExam(cssClass, idEducationTypeSelected,idExam){
	$('input[id$="hfCTClick"]').val(0);
	$('input[id$="hfExamClick"]').val(idExam);
	showPopupSubscribe(cssClass, idEducationTypeSelected);
}

function showPopupSubscribe(cssClass, idEducationTypeSelected){
	showPopup(cssClass);
	$('input[id$="hfSelectedEducationType"]').val(idEducationTypeSelected);
}

function showPopupNotDownloadContent(cssClass, idEducationTypeSelected){
	showPopup(cssClass);
}

function showPopupBrokenLink(cssClass, idContentType, idModule) {
    showPopup(cssClass);
    $('input[id$="hfSelectedMaterialReport"]').val(idContentType);
    $('input[id$="hfModuleIdReport"]').val(idModule);
    $('input[id$="hfEtIdReport"]').val($('input[id$="hfIdEducationType"]').val());
}

function disablePopupBrokenLink() {
    disablePopup($(".popupBrokenLink"));
}

function showPopUpInvitation(cssClass) {
    var mask = popup_createMask();
    mask.fadeIn(1000, function() {
    loadPopupInvitation($(cssClass));
    centerPopupInvitation($(cssClass));
    });
}

function SetStyleTags() {
    var flag = false;
    $('.my-tags-list input:checkbox').each(function () {
        if (!$(this).attr("flag")) {
            if ($(this).attr("checked") == true) {
                $(this).next("label").addClass("active");
            }
            $(this).attr("flag", "true");
            flag = true;
        }
    });

    if (flag) {
        $('.my-tags-list input:checkbox').click(function () {
            $(this).next("label").toggleClass("active");
        });
    }
}
function getNextLevel(level) {
    if (level == "Bronze") {
        return "Silver";
    }
    else if (level == "Silver") {
        return "Gold";
    }
    else if (level == "Gold") {
        return "Platinum";
    }
    return "";
}

function getPercetangeByLevel(level) {
    if (level == "Bronze") {
        return 0;
    }
    else if (level == "Silver") {
        return 35;
    }
    else if (level == "Gold") {
        return 70
    }
    else if (level == "Platinum") {
        return 100;
    }
    return -1;
}

function getPercetangeByNextLevel(level) {
    return getPercetangeByLevel(getNextLevel(level));    
}

function refreshMembershipUserProgress(membershipLevel, points, minPoints, maxPoints) {
    var percentage = 0;
    if (membershipLevel == "Platinum") {
        percentage = getPercetangeByLevel(membershipLevel);
    }
    else {
        percentageE = (points - minPoints) / (maxPoints - minPoints) * 100;

        pByLevel = getPercetangeByLevel(membershipLevel);

        percentage = pByLevel + percentageE * (getPercetangeByNextLevel(membershipLevel) - pByLevel) / 100;
    }
    $('#completed_progress').animate({width: percentage + "%"},4000,null);
}

function DefaultButtonExtendedTextBox() {
    $(".extendedtextbox input").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(this).parent().find(".textbox_image").click();
            //$('button[type=submit] .default').click();
            return false;
        } else {
            return true;
        }
    });
}

function initSelectboxes() {
    $(".selectbox").selectbox();
}

function showPopupCountries(targetClass) {
    var mask = popup_createMaskCountries();
    mask.fadeIn(1000, function () {
        loadPopupCountries($("." + targetClass));
        centerPopupCountries($("." + targetClass));
    });
}
function showPopupBookmarks(targetClass) {
    var mask = popup_createMaskCountries();
    mask.fadeIn(1000, function () {
        loadPopupCountries($("." + targetClass));
        centerPopupCountries($("." + targetClass));
    });
}

function showPopUpMessageTakeExam() {
    showPopup("popUpMessageTakeExam");
}

function wrapText() {
    $('*[wrapInMaxLength]').each(function() {
        if ($(this).attr("setWrap") != "true") {
            var maxLength = $(this).attr("wrapInMaxLength");
            var content = $(this).html().trim();
            var words = content.split(" ");
            var finalContent = "";
            jQuery.each(words, function(j) {
                if (finalContent != "") {
                    finalContent = finalContent + " ";
                }
                var word = this;
                if (word.length > maxLength) {
                    var iterations = parseInt((word.length / maxLength));
                    for (i = 0; i < (iterations + 1); i++) {
                        var init = (i * maxLength);
                        if (init < word.length) {
                            finalContent = finalContent + content.substr(init, maxLength) + "&#8203;";
                        }
                    }
                }
                else {
                    finalContent = finalContent + word;
                }
            });
            $(this).attr("setWrap", "true");
            $(this).empty();
            partialContent = finalContent;
            partialContent = finalContent.replace("\n", "<br/>");
            while (partialContent != finalContent) {
                finalContent = partialContent;
                partialContent = finalContent.replace("\n", "<br/>");
            }
            $(this).append(finalContent);
        }
    });
}

function showPanelEducationType(tdSelect) {
    var tabs = $(".EducationTab");
        jQuery.each(tabs, function() {
        $(this).attr("class", "off EducationTab");
    });

    $(tdSelect).attr("class", "on EducationTab");
}

function showPanelMaterial(tdSelect) {
    var tabs = $(".MaterialTab");
    jQuery.each(tabs, function() {
        $(this).attr("class", "off MaterialTab");
        pnlID = $(this).attr("panelID");
        $("#" + pnlID).hide();
    });

    $(tdSelect).attr("class", "on MaterialTab");
    pnlID = $(tdSelect).attr("panelID");
    $("#" + pnlID).show();
}
function showPanelCommunity(tdSelect) {
    var tabs = $(".CommunityTab");
        jQuery.each(tabs, function() {
        $(this).attr("class", "off CommunityTab");
    });

    $(tdSelect).attr("class", "on CommunityTab");
}

function ValidateEmptyFieldsAndMinLength(minlength) {
    var list = $(".filter");
    var valid = false;
    jQuery.each(list, function(i) {
        var str = $(this).attr("value");
        if (jQuery.trim(str) != "" && jQuery.trim(str).length > minlength) {
            valid = true;
        }
    });

    return valid;
}

function SetUniqueRadioButton(nameregex, rid) {
    re = new RegExp(nameregex);
    rb = document.getElementById(rid);
    var inputs = document.getElementsByTagName('input');
    for (i = 0; i < inputs.length; i++) {
        elm = inputs[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name)) {
                elm.checked = false;
            }
        }
    }

    rb.checked = true;
}

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!
function loadPopup(target) {
    //loads popup only if it is disabled
    if (popupStatus == 0) {
        /*$(".IFramePopUp").css({
            "opacity": "0.0"
        });
        $(".backgroundPopup").css({
            "opacity": "0.7"
        });*/

        //$(".IFramePopUp").fadeIn("normal");
        //$(".backgroundPopup").fadeIn("normal");
        target.fadeIn("normal", function() {
			if(target.hasClass("popUpFinalizedExam"))
			{
				loadCarousel();
			}
		});
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup(target) {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        $(".IFramePopUp").fadeOut("normal");
        $(".backgroundPopup").fadeOut("normal",
            function() {
            jQuery(this).remove();
       });
        target.fadeOut("normal");
        popupStatus = 0;
    }
}

//centering popup
function centerPopup(target) {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = target.height();
    var popupWidth = target.width();

    //centering
    target.css({
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });

    //only need force for IE6
    $(".backgroundPopup").css({
        "height": windowHeight
    });

}


/*POP UP Countries*/

function loadPopupCountries(target) {
    //loads popup only if it is disabled
    if (popupStatus == 0) {
        $(".IFramePopUpCountries").css({
            "opacity": "0.0"
        });
        $(".backgroundPopupCountries").css({
            "opacity": "0.7"
        });

        //$(".IFramePopUpCountries").fadeIn("normal");
        //$(".backgroundPopupCountries").fadeIn("normal");
        target.fadeIn("normal");
        target.css('display', 'block');
        popupStatus = 1;
    }
}

function centerPopupCountries(target) {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = target.height();
    var popupWidth = target.width();

    //centering
    target.css({
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });

    //only need force for IE6
    $("#backgroundPopupCountries").css({
        "height": windowHeight
    });

}
function disablePopupCountries(target) {
    if (popupStatus == 1) {
        $(".IFramePopUpCountries").fadeOut("normal");
        $(".backgroundPopupCountries").fadeOut("normal",
            function() {
                jQuery(this).remove();
        });
        target.fadeOut("normal");
        popupStatus = 0;
    }
}


/*POP UP INVITATION*/

//loading popup with jQuery magic!
function loadPopupInvitation(target) {
    //loads popup only if it is disabled
    if (popupStatus == 0) {
        target.fadeIn("normal");
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopupInvitation(target) {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        $(".backgroundPopup").fadeOut("normal",
            function() {
                jQuery(this).remove();
            });
        target.fadeOut("normal");
        popupStatus = 0;
    }
}

function disablePopUpShareMail() {
    disablePopupInvitation($('.popUpShareByMail'));
}

function disablePopUpInvitation() {
    disablePopupInvitation($('.popUpInvitation'));
}

//centering popup
function centerPopupInvitation(target) {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = target.height();
    var popupWidth = target.width();

    //centering
    target.css({
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });

}

/*REQUEST HANDLERS*/

//Register Begin Request and End Request
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);

function BeginRequestHandler(sender, args) {
    $(":submit").attr("disabled", "disabled");
    var element = args.get_postBackElement();
    showUpdateProgress($(element));
}

function EndRequestHandler(sender, args) {
    $(":submit").attr("disabled", "");
    initSelectboxes();
    hideUpdateProgress();
    wrapText();
    BindConfirmationPopup();
    DefaultButtonExtendedTextBox();
    SetStyleTags();
}

function InitializeRequest(sender, args) {

    var element = args.get_postBackElement();
    var jelement = $(element);

    if (jelement.attr("filterType") == "ValidateEmptyFieldsAndMinLength") {
        min = $(element).attr("minLengthRequired");
        var valid = ValidateEmptyFieldsAndMinLength(min);

        if (valid) {
            $("#tdNotFilter").hide();
        } else {
            $("#tdNotFilter").show();
            args.set_cancel(true);
        }
    }
    // Bindear click de los Buttons con popup de ocnfirmacion
    var showConfirmationPopUp = jelement.attr("showConfirmationPopUp");
    if (showConfirmationPopUp) {
        if (showConfirmationPopUp == "true") {
            //event.preventDefault();
            args.set_cancel(true);

            LoadConfirmationPopupForTriggerButton(jelement);
        }
        else {
            jelement.attr("showConfirmationPopUp", "true");

            classPopUp = jelement.attr("popUpConfirm");

            disablePopup($("." + classPopUp));
        }
    }
}

function showUpdateProgress(trigger) {
    var showUpdateProgress = trigger.attr("showupdateprogress");
    if (showUpdateProgress == "false") {
        $("#divUpdateProgress").hide();
    }

    // TODO allow many comma-separated element Ids at blockOnUpdate
    var blockOnUpdate = trigger.attr("blockOnUpdate");
    if (blockOnUpdate) {
        var block_element = $("#" + blockOnUpdate);
        if (block_element) {
            // hide full update progress panel
            $("#divUpdateProgress").hide();
            // add blocker element and animate it
            blocker = $("<div class='blockOnUpdateBlocker'><div></div></div>");
            block_element.append(blocker);
            blocker.fadeIn(300);
        }
    }
}

function hideUpdateProgress() {
    // reset full update progress
    $("#divUpdateProgress").show();
    
    // remove blockers
    $(document).find(".blockOnUpdateBlocker").fadeOut(200,
        function() {
            $(this).remove();
        });
}


// Bindear click de los HyperLinks con popup de confirmacion
BindConfirmationPopup();

function BindConfirmationPopup() {
    $(document).ready(function () {
        $('a[showconfirmationpopup][href]').click(function () {
            if ($(this).attr("isBindPopUp") == "true") {
                $(this).attr("isBindPopUp", "true")
                LoadConfirmationPopupForTriggerLink($(this));
                return false;
            }
        });
    });
}

function LoadConfirmationPopupForTriggerLink(jelement) {
    LoadConfirmationPopupCommonTrigger(jelement);

    // copy trigger's href to confirm button href
    var propConfirmButton = jelement.attr("buttonConfirm");
    $('*[' + propConfirmButton + ']').attr("href", jelement.attr("href")); 
}

function LoadConfirmationPopupForTriggerButton(jelement) {
    LoadConfirmationPopupCommonTrigger(jelement);

    // set trigger post back to confirm button
    var propConfirmButton = jelement.attr("buttonConfirm");
    
    var clientID = jelement.attr("id");
    var uniqueID = clientID.replace(/_/g, "$");
    
    $('*[' + propConfirmButton + ']').attr("href", "javascript:__doPostBack('" + uniqueID + "', '');");
}

function panelCollapsable(divID,targetID) {
    $("#" + divID).toggleClass("opened");
    $("#" + divID).toggleClass("closed");
    $("#" + targetID).slideToggle("slow");
}
function LoadConfirmationPopupCommonTrigger(jelement) {

    jelement.attr("showConfirmationPopUp", "false");

    classPopUp = jelement.attr("popUpConfirm");

    showPopup(classPopUp);

    propCancelButton = jelement.attr("buttonCancel");

    clientID = jelement.attr("id");
    $('*[' + propCancelButton + ']').attr("idTarget", clientID);
}

function popup_createMask() {
    //Get the screen height and width
    var maskHeight = jQuery(document).height();
    var maskWidth = jQuery(window).width();

    // create mask
    var mask = jQuery("<div class='backgroundPopup'></div>");
    mask.appendTo("body");

    //Set height and width to mask to fill up the whole screen
    mask.css({ 'width': maskWidth,
        'height': maskHeight,
        'opacity': 0.5
    });
    return mask;
}

function popup_createMaskCountries() {
    //Get the screen height and width
    var maskHeight = jQuery(document).height();
    var maskWidth = jQuery(window).width();

    // create mask
    var mask = jQuery("<div class='backgroundPopupCountries'></div>");
    mask.appendTo("body");

    //Set height and width to mask to fill up the whole screen
    mask.css({ 'width': maskWidth,
        'height': maskHeight,
        'opacity': 0.5
    });
    return mask;
}

function showPopup(cssClass) {
    var mask = popup_createMask();
    mask.fadeIn(1000, function() {
        centerPopup($("." + cssClass));
        loadPopup($("." + cssClass));
    });
}

function ShowDetailsEducationType(idContainer, idhfLastChangeSelectedItem) {
    lastChangeSelectedItemID = $("#" + idhfLastChangeSelectedItem).attr("value");
    var idImageSelected = idContainer + "_imgArrowS";
    var idImageNoSelected = idContainer + "_imgArrowNS";
    var idDivContainer = idContainer + "_divContainer";
    var idDescription = idContainer + "_description";

    var flag = false;
    if (lastChangeSelectedItemID != "") {
        $("#" + lastChangeSelectedItemID + "_imgArrowS").hide();
        $("#" + lastChangeSelectedItemID + "_imgArrowNS").show();
        $("#" + lastChangeSelectedItemID + "_divContainer").attr("class", "closed");
        $("#" + lastChangeSelectedItemID + "_description").hide(-1,
            function() {
                flag = true;
                if (idContainer != lastChangeSelectedItemID) {
                    $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
                    $("#" + idImageSelected).show();
                    $("#" + idImageNoSelected).hide();
                    $("#" + idDescription).slideDown("normal");
                    $("#" + idDivContainer).attr("class", "open");

                }
                else {
                    $("#" + idhfLastChangeSelectedItem).attr("value", "");
                }
            }
        );
    }

    if (!flag) {
        if (idContainer != lastChangeSelectedItemID) {
            $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
            $("#" + idImageSelected).show();
            $("#" + idImageNoSelected).hide();
            $("#" + idDescription).slideDown("normal");
            $("#" + idDivContainer).attr("class", "open");

        }
        else {
            $("#" + idhfLastChangeSelectedItem).attr("value", "");
        }
    }
}

function ShowDetailsCommunity(idContainer, idhfLastChangeSelectedItem) {
    lastChangeSelectedItemID = $("#" + idhfLastChangeSelectedItem).attr("value");
    var idImageSelected = idContainer + "_imgArrowS";
    var idImageNoSelected = idContainer + "_imgArrowNS";
    var idDivContainer = idContainer + "_divContainer";
    var idDescription = idContainer + "_description";

    var flag = false;
    if (lastChangeSelectedItemID != "") {
        $("#" + lastChangeSelectedItemID + "_imgArrowS").hide();
        $("#" + lastChangeSelectedItemID + "_imgArrowNS").show();
        $("#" + lastChangeSelectedItemID + "_divContainer").attr("class", "closed");
        $("#" + lastChangeSelectedItemID + "_description").hide(-1,
            function() {
                flag = true;
                if (idContainer != lastChangeSelectedItemID) {
                    $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
                    $("#" + idImageSelected).show();
                    $("#" + idImageNoSelected).hide();
                    $("#" + idDescription).slideDown("normal");
                    $("#" + idDivContainer).attr("class", "open");

                }
                else {
                    $("#" + idhfLastChangeSelectedItem).attr("value", "");
                }
            }
        );
    }

    if (!flag) {
        if (idContainer != lastChangeSelectedItemID) {
            $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
            $("#" + idImageSelected).show();
            $("#" + idImageNoSelected).hide();
            $("#" + idDescription).slideDown("normal");
            $("#" + idDivContainer).attr("class", "open");

        }
        else {
            $("#" + idhfLastChangeSelectedItem).attr("value", "");
        }
    }
}

function ShowDetailsMessage(idContainer, idhfLastChangeSelectedItem) {
    lastChangeSelectedItemID = $("#" + idhfLastChangeSelectedItem).attr("value");

    var idImageSelected;
    var idImageNoSelected
    if ($("#" + idContainer + "_pnlMessage").attr("class") == "new") {
        idImageSelected = idContainer + "_imgNewSelect";
        idImageNoSelected = idContainer + "_imgNewNotSelect";    
    }
    else {
        idImageSelected = idContainer + "_imgSelect";
        idImageNoSelected = idContainer + "_imgNotSelect";    
    }
    
    var idDivContainer = idContainer + "_divContainer";
    var idBody = idContainer + "_body";
    var flag = false;
    if (lastChangeSelectedItemID != "") {
        if ($("#" + lastChangeSelectedItemID + "_pnlMessage").attr("class") == "new") {
            $("#" + lastChangeSelectedItemID + "_imgNewSelect").hide();
            $("#" + lastChangeSelectedItemID + "_imgNewNotSelect").show();
        }
        else {
            $("#" + lastChangeSelectedItemID + "_imgSelect").hide();
            $("#" + lastChangeSelectedItemID + "_imgNotSelect").show();
        }
        $("#" + lastChangeSelectedItemID + "_divContainer").attr("class", "closed");
        $("#" + lastChangeSelectedItemID + "_body").hide(-1,
            function() {
                flag = true;
                if (idContainer != lastChangeSelectedItemID) {
                    $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
                    $("#" + idImageSelected).show();
                    $("#" + idImageNoSelected).hide();
                    $("#" + idBody).slideDown("normal");
                    $("#" + idDivContainer).attr("class", "open");
                }
                else {
                    $("#" + idhfLastChangeSelectedItem).attr("value", "");
                }
            }
        );
    }

    if (!flag) {
        if (idContainer != lastChangeSelectedItemID) {
            $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
            $("#" + idImageSelected).show();
            $("#" + idImageNoSelected).hide();
            $("#" + idBody).slideDown("normal");
            $("#" + idDivContainer).attr("class", "open");
        }
        else {
            $("#" + idhfLastChangeSelectedItem).attr("value", "");
        }
    }
}

function ShowDetailsConversation(idContainer, idhfLastChangeSelectedItem) {
    lastChangeSelectedItemID = $("#" + idhfLastChangeSelectedItem).attr("value");

    var idImageSelected = idContainer + "_imgSelect";
    var idImageNoSelected = idContainer + "_imgNotSelect";
   

    var idDivContainer = idContainer + "_divContainer";
    var idBody = idContainer + "_body";

    var flag = false;
    if (lastChangeSelectedItemID != "") {
        $("#" + lastChangeSelectedItemID + "_divContainer").attr("class", "closed");
        $("#" + lastChangeSelectedItemID + "_imgSelect").hide();
        $("#" + lastChangeSelectedItemID + "_imgNotSelect").show();

        $("#" + lastChangeSelectedItemID + "_body").hide(-1, function() {
            flag = true;
            if (idContainer != lastChangeSelectedItemID) {
                $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
                $("#" + idDivContainer).attr("class", "open");
                $("#" + idImageSelected).show();
                $("#" + idImageNoSelected).hide();
                $("#" + idBody).slideDown("normal");
            }
            else {
                $("#" + idhfLastChangeSelectedItem).attr("value", "");
            }
        });
    }

    if (!flag) {
        if (idContainer != lastChangeSelectedItemID) {
            $("#" + idhfLastChangeSelectedItem).attr("value", idContainer);
            $("#" + idDivContainer).attr("class", "open");
            $("#" + idImageSelected).show();
            $("#" + idImageNoSelected).hide();
            $("#" + idBody).slideDown("normal");
        }
        else {
            $("#" + idhfLastChangeSelectedItem).attr("value", "");
        }
    }
}

function Conversation_SetDataPopUp(idMessageReply, hfIdMessageReply, lnkReplyUniqueID) {
    showPopup("popUpReply");
    $("#" + hfIdMessageReply).attr("value", idMessageReply);
    __doPostBack(lnkReplyUniqueID, '');
}

function Conversation_ClearPopUp(lnkClosePopUpUniqueID) {
    disablePopup($(".popUpReply"));
    __doPostBack(lnkClosePopUpUniqueID, '')
}

/*EDUCATION DETAILS*/
function EducationDetais_ClosePopUp(lnkClosePopUpUniqueID) {
    disablePopup($(".popUpMessage"));
    __doPostBack(lnkClosePopUpUniqueID, '')
}

function EducationDetais_ClosePopUp() {
    disablePopup($(".popUpMessage"));
}

function checkBox_selectChange(divContainer) {
    hfSelectID = $(divContainer).attr("hfSelectedID");
    imageOnID = $(divContainer).attr("imageOnID");
    imageOffID = $(divContainer).attr("imageOffID");
    hfAutoPostBackID = $(divContainer).attr("hfAutoPostBackID");
    if ($("#" + hfSelectID).attr("value") == "true") {
        $("#" + imageOnID).hide(-1,
        function() {
            $("#" + imageOffID).show(-1,
                function() {
                    $("#" + hfSelectID).attr("value", "false");
                });
            }
        );
    }
    else {
        $("#" + imageOnID).show(-1,
        function() {
            $("#" + imageOffID).hide(-1,
                function() {
                    $("#" + hfSelectID).attr("value", "true");
                }
            );
        }
    );
    }
    
    if ($("#" + hfAutoPostBackID).attr("value") == "true") {
        hfAutoPostBackID = $(divContainer).attr("hfAutoPostBackID");
        lnkSelectChangeUniqueID = $(divContainer).attr("lnkSelectChangeUniqueID");
        __doPostBack(lnkSelectChangeUniqueID, '');
    }
}

function CollapseExpandEffect(action) {
    targetID = $(action).attr("target");
    collapseImageID = $(action).attr("collapseImage");
    expandImageID = $(action).attr("expandImage");
    $("#" + collapseImageID).toggle();
    $("#" + expandImageID).toggle(-1, function() {
        $("#" + targetID).slideToggle("normal");
    });   
}

function ShowPopUpMessage(lnkAdminMessageUniqueID) {
    showPopup("popUpMessage");
    __doPostBack(lnkAdminMessageUniqueID, '');

}

/***** HightLight Gridview Rows on MouseOver ****/
function Highlight(row) {
    $(row).attr("class","highlight");
}
function UnHighlight(row) {
    $(row).attr("class", "unHighlight");
}

function effectTabs(object) {
    $("*[ispaneltab]").hide();
    allTabs = $("*[istab]");
    jQuery.each(allTabs, function(i) {
        $(this).attr("class", $(this).attr("no-selected-class"));
        var cornerID = $(this).attr("corner");
        $(cornerID).attr("class", $(cornerID).attr("no-selected-class"));

        var horizontalID = $(this).attr("horizontal");
        $(horizontalID).attr("class", $(horizontalID).attr("no-selected-class"));

        var verticalID = $(this).attr("vertical");
        $(verticalID).attr("class", $(verticalID).attr("no-selected-class"));
    });
    panel = $(object).attr("target");
    $("#" + panel).show();
    $(object).attr("class", "selected");
    cornerID = $(object).attr("corner");
    $(cornerID).attr("class", $(cornerID).attr("selected-class"));

    verticalID = $(object).attr("vertical");
    $(verticalID).attr("class", $(verticalID).attr("selected-class"));

    horizontalID = $(object).attr("horizontal");
    $(horizontalID).attr("class", $(horizontalID).attr("selected-class"));
}



function openNewWindow(url) {
    window.open(url);
}

function setStylesInCalendar() {
    tdTitleMonth = $(".calendar-title tr td")[1];
    $(tdTitleMonth).css({ "width": "160px" });
    wordsMonth = $(tdTitleMonth).html().split(" ");
    if (wordsMonth.length == 3) {
        $(tdTitleMonth).empty();
        $(tdTitleMonth).append(wordsMonth[0] + " " + wordsMonth[2]);
    }
    
    applicationPath = $(".styleInformationCalendar").attr("applicationPath");
    imgPrev = "<img id='idBack' class='imgCalendar' style='border-width: 0px; vertical-align: bottom; padding-right: 3px;' src='" + applicationPath + "/Images/blue_arrow_left.png'/>";
    imgNext = "<img id='idBack' class='imgCalendar' style='border-width: 0px; vertical-align: bottom; padding-right: 3px;' src='" + applicationPath + "/Images/blue_arrow_right.png'/>";
    aHref = $(".next-prev a");
    jQuery.each(aHref, function(i) {
        $(this).empty();
        if (i == 0) {
            $(this).append(imgPrev);
            $(this).attr("title", $(".styleInformationCalendar").attr("PrevMonthToolTip"));
        }
        else {
            $(this).append(imgNext);
            $(this).attr("title", $(".styleInformationCalendar").attr("NextMonthToolTip"));
        }
    });
}

function setSelectedDatesInMonth(selectedDates,isTodayInMonth) {
    tdsDays = $(".day-number a");
    dates = selectedDates.split(",");
    jQuery.each(tdsDays, function() {
    
        for (i = 0; i < dates.length; i++) {
            if ($(this).html() == dates[i]) {
                $(this).css({ "color": "#ff8040", "text-decoration": "none" });
                break;
            }
        }
    });
    if (isTodayInMonth) {
        for (i = 0; i < dates.length; i++) {
            if ($(".today-day a").html() == dates[i]) {
                $(".today-day a").css({ "color": "#ff8040", "text-decoration": "none" });
            }
        }
    }
}

function setSelectedDatesInPrevMonth(selectedDates,isTodayInMonth) {
    tdsDays = $(".other-month-day a");
    dates = selectedDates.split(",");
    flag = false;
    jQuery.each(tdsDays, function() {
        if ($(this).html() == 1) {
            flag = true;
        }
        if (!flag) {
            for (i = 0; i < dates.length; i++) {
                if ($(this).html() == dates[i]) {
                    $(this).css({ "color": "#ff8040", "text-decoration": "none" });
                    break;
                }
            }
        }
    });

    if (isTodayInMonth) {
        for (i = 0; i < dates.length; i++) {
            if ($(".today-day a").html() == dates[i]) {
                $(".today-day a").css({ "color": "#ff8040", "text-decoration": "none" });
            }
        }
    }
}

function setSelectedDatesInNextMonth(selectedDates,isTodayInMonth) {
    tdsDays = $(".other-month-day a");
    dates = selectedDates.split(",");
    flag = false;
    jQuery.each(tdsDays, function() {
        if ($(this).html() == 1) {
            flag = true;
        }
        if (flag) {
            for (i = 0; i < dates.length; i++) {
                if ($(this).html() == dates[i]) {
                    $(this).css({ "color": "#ff8040", "text-decoration": "none" });
                    break;
                }
            }
        }
    });

    if (isTodayInMonth) {
        for (i = 0; i < dates.length; i++) {
            if ($(".today-day a").html() == dates[i]) {
                $(".today-day a").css({ "color": "#ff8040", "text-decoration": "none" });
            }
        }
    }
}

function disablePopUpShare() {
    disablePopup($('.popUpShare'));
}

function disablePopUpSubscribeToTeam() {
    disablePopup($('.popUpSubscribeToTeam'));
}

/***************** TIME ********************/

function timeToFormatString(time) {
    var tm = new Date(time * 1000);
    var hours = tm.getUTCHours();
    var minutes = tm.getUTCMinutes();
    var seconds = tm.getUTCSeconds();

    return twoDigits(hours) + ':' + twoDigits(minutes) + ':' + twoDigits(seconds);
}

function twoDigits(x) {
    return ((x > 9) ? "" : "0") + x
}


/****************** TEXT WIDTH **************/

// This function calculates width of text contained within an html tag, regardless of his css.
$.fn.textWidth = function() {
    var html_org = $(this).html();
    var html_calc = '<span>' + html_org + '</span>'
    $(this).html(html_calc);
    var width = $(this).find('span:first').width();
    $(this).html(html_org);
    return width;
};


/*** EDUCATION TYPE DETAIL ***/

function myMutex() {
    this.value = 1;
}
var mutex = new myMutex();

function lock(mutex) {
    if (mutex.value == 1) {
        mutex.value = 0;
        return true;
    }
    return false;
}
function unlock(mutex) {
    mutex.value = 1;
}

function isApproved() {
    return $('input[id$="hfIsApproved"]').val();
}

function getIdETP() {
    return $('input[id$=hfIdEducationType"]').val();
}

function getNumControlSelected() {
    return parseInt($("#hfNumControlSelected").attr("value"));
}

function setNumControlSelected(num) {
    $("#hfNumControlSelected").attr("value", num);
}


function getAllDocuments() {
    return $('input[id$="hfAllDocuments"]').attr("value");
}

function setAllDocuments(value) {
    $('input[id$="hfAllDocuments"]').attr("value", value);
}


function getPendingDocuments() {
    return $('input[id$="hfPendingDocuments"]').attr("value");
}

function setPendingDocuments(value) {
    $('input[id$="hfPendingDocuments"]').attr("value", value);
}

function getPendingExamsCount() {
    return $('input[id$="hfPendingExamsCount"]').attr("value");
}

function setPendingExamsCount(value) {
    $('input[id$="hfPendingExamsCount"]').attr("value", value);
}

function getSelectedIsEnabled() {
    return $('input[id$="hfSelectedIsEnabled"]').attr("value");
}

function setSelectedIsEnabled(value) {
    $('input[id$="hfSelectedIsEnabled"]').attr("value", value);
}



function reducePendingDocuments() {
    setPendingDocuments(getPendingDocuments() - 1);
    refreshShowDocuments();
}

$(document).ready(function () {
    $("#ContainerBackPanels").click(function (event) {
        if (lock(mutex)) {
            var numControl = getNumControlSelected();
            if (numControl == 1)
                numControl = 0;
            divSelected = $('div[numbercontrol="' + (numControl) + '"]');
            $(divSelected).find(".progress_icon_selected").attr("class", "progress_icon_no_selected");
			//TODO:review
			$('div[isShow="true"]').hide();

            scrollLastPanelsRight(numControl + 1, panelIsVisible());
            setNumControlSelected(--numControl);

            $("#pnlTabsModule").hide();
            $("#pnlDocumentsModule").hide();

            visibilityBackPanel();

            unlock(mutex);
        }
    });
});

function showNextEducationTypes(idEducationTypeSelected, idEducationLevelSelected, isSubscribe, numControl, selectedTD) {
    if (lock(mutex)) {
        setNumControlSelected(numControl);
        var selectedIsEnabled = tdNormal = $(selectedTD).find("div[_isenabled]").attr("_isenabled");
        idEducationType = parseInt($('input[id$="hfIdEducationType"]').attr("value"));
        culture = $('input[id$="hfCulture"]').attr("value");
		
		var params = {
			   idEducationTypeSelected: idEducationTypeSelected,
			   idEducationLevelSelected: idEducationLevelSelected,
			   isSubscribe: isSubscribe,
			   selectedIsEnabled: selectedIsEnabled,
			   numControl: numControl,
			   isApproved: isApproved(),
			   idEducationType: idEducationType,
			   culture: culture
			 };
			 
		CallAJAXPost("Studies/EducationDetails.aspx/ShowNextEducationTypes", params, showNextEducationTypes_onSuccess, showNextEducationTypes_onFailed);
		
		showUpdateProgress($("#lnkBlockOnUpdate"));
        controlSelected(selectedTD);
    }
}

function showNextEducationTypes_onSuccess(result) {
    HideError();
    nextControl = $('div[numbercontrol="' + (getNumControlSelected() + 1) + '"]');

    if ($(nextControl).attr("numbercontrol")) {
        $(nextControl).replaceWith(result);
    }
    else {
		//$("<div>Leonardo</div>").insertAfter($('div[numbercontrol="' + (getNumControlSelected()) + '"]'));
        $(result).insertAfter($('div[numbercontrol="' + (getNumControlSelected()) + '"]'));
    }
    visibilityBackPanel();

    scrollPanelsLeft(getNumControlSelected() + 1, false);
	
	hideUpdateProgress()
    unlock(mutex);
}

function showNextEducationTypes_onFailed(error) {
	hideUpdateProgress();
    unlock(mutex);
}

function showNextPanelEducationTypes(idEducationTypeSelected, idEducationLevelSelected, isSubscribe, numControl, selectedTD) {
    if (lock(mutex)) {
        var moduleControl = $("#module-" + idEducationTypeSelected)
        $('div[isShow="true"]').each(function () {
            if ($(this).attr("id") != ("module-" + idEducationTypeSelected)) {
                var id = $(this).attr("etID");
                var control = $('span[class="etype"][this="' + id + '"]').find(".progress_name_icon");
                if (control.attr("class") == "progress_name_icon")
                {
                    control.addClass("closed");
                }
                $(this).hide();
            }
        });

        if (moduleControl.css("display") == "block") {
            moduleControl.hide();

            unlock(mutex);
            return;
        }
        
        setNumControlSelected(numControl);
        var selectedIsEnabled = tdNormal = $(selectedTD).find("div[_isenabled]").attr("_isenabled");
		idEducationType = parseInt($('input[id$="hfIdEducationType"]').attr("value"));
        var culture = $('input[id$="hfCulture"]').attr("value");


		var params = {
			   idEducationTypeSelected: idEducationTypeSelected,
			   idEducationLevelSelected: idEducationLevelSelected,
			   isSubscribe: isSubscribe,
			   selectedIsEnabled: selectedIsEnabled,
			   numControl: numControl,
			   idEducationType: idEducationType,
			   isApproved: isApproved(),
			   culture: culture
			 };
			 
		CallAJAXPost("Studies/EducationDetails.aspx/ShowNextPanelEducationTypes", params, showNextPanelEducationTypes_onSuccess, showNextPanelEducationTypes_onFailed);
		
		showUpdateProgress($("#lnkBlockOnUpdate"));
        controlSelected(selectedTD);
    }
}

function controlSelected(selectedTD) {
    divSelected = $(selectedTD).parent().parent().find("div.progress_icon_selected");
    $(divSelected).attr("class", "progress_icon_no_selected");
    $(selectedTD).find(".progress_icon_no_selected").attr("class", "progress_icon_selected");
}

function refreshShowDocuments() {
    if (getSelectedIsEnabled() == "false") {
        return;
    }

    if (isApproved() == "true") {
        return;
    }
}

function removeIconInProgress(div) {
    $(div).removeClass("in_progress");
}

function addIconInProgress(div) {
    $(div).addClass("in_progress");    
}

function showNextPanelEducationTypes_onSuccess(result) {
    var flag = false;
    var showModule = true;
    if (result["Type"] == "Module") {
        showNextPanelEducationTypes_module(result);
    }
    else {
        showModule = false;
        flag = panelIsVisible();
        
        $("#pnlTabsModule").hide();
        $("#pnlDocumentsModule").hide();
        var html = result["HtmlResponse"];
        nextControl = $('div[numbercontrol="' + (getNumControlSelected() + 1) + '"]');

        if ($(nextControl).attr("numbercontrol")) {
            $(nextControl).replaceWith(html);
        }
        else {
            $(html).insertAfter($('div[numbercontrol="' + (getNumControlSelected()) + '"]'));
        }
    }
    //visibilityBackPanel();

    if (flag) {
        //expandPanel();
    }
    else {
        //scrollPanelsLeft(getNumControlSelected() + 1, showModule);
    }
	hideUpdateProgress()
	
    unlock(mutex);
}

function showNextPanelEducationTypes_module(result) {
    var controlModule = $("#module-" + result["IdEducationType"]);
    controlModule.attr("isShow", "true");
    controlModule.show();

    setSelectedIsEnabled(result["SelectedIsEnabled"]);

    showNextPanelEducationTypes_module_description(result);
    showNextPanelEducationTypes_module_requisites(result);
    showNextPanelEducationTypes_module_exams(result,controlModule);
	showNextPanelEducationTypes_module_supplementaryMaterials(result,controlModule);
    showNextPanelEducationTypes_module_documents(result, controlModule);
	showNextPanelEducationTypes_module_vote(result, controlModule);
	showNextPanelEducationTypes_module_share(result, controlModule);

    BindConfirmationPopup();
}

function showNextPanelEducationTypes_module_description(result) {
    var desc = $.trim(result["ModuleDescription"]);
    if (desc.length > 0) {
        $("#module-description").show();
        $("#moduleDescription").html(desc);
    }
    else {
        $("#module-description").hide();
    }
}

function showNextPanelEducationTypes_module_requisites(result) {
    if (result["CountRequisites"] > 0) {
        $("#module-requisites").show();
        $("#moduleRequisites").html(result["HtmlResponseRequisites"]);
    }
    else {
        $("#module-requisites").hide();
    }
}

function showNextPanelEducationTypes_module_exams(result, moduleControl) {
    if (result["CountExams"] > 0) {
        setPendingExamsCount(result["PendingExams"]);
    }
    else {
    }
	if (result["ShowSupplementaryMaterials"].toLowerCase() == "false")
	{
		$(".module-exams-title").show();
		moduleControl.find('#pnlExam').html(result["HtmlResponseExams"]);
	}
	else
	{
		$(".module-exams-title").hide();
	}
}

function showNextPanelEducationTypes_module_supplementaryMaterials(result, moduleControl) {
    if (result["ShowSupplementaryMaterials"].toLowerCase() == "true" && result["CountSupplementaryMaterials"] != "0")
	{
		$(".module-supplementary-materials-title").show();
		moduleControl.find('#pnlSuppelementaryMaterials').html(result["HTMLResponseSupplementaryMaterials"]);
	}
	else
	{
		$(".module-supplementary-materials-title").hide();
	}
}

function showNextPanelEducationTypes_module_documents(result,moduleControl) {
    setPendingDocuments(result["PendingDocuments"]);

    if (result["CountDocuments"] > 0) {

        $("#module-materials").show();
        setAllDocuments(result["CountDocuments"]);
        refreshShowDocuments();
        moduleControl.find('#pnlMaterials').html(result["HtmlResponseMaterials"]);
    }
    else {
        $("#module-materials").hide();
    }
}

function showNextPanelEducationTypes_module_vote(result) {
    var votePositive = result["VotePositive"] ? $.trim(result["VotePositive"]) : "";
	var voteNegative = result["VoteNegative"] ? $.trim(result["VoteNegative"]) : "";
    if (votePositive.length > 0) {
		$("#module-" + result["IdEducationType"] + " #share-buttons .module-vote-positive").show();
        $("#module-" + result["IdEducationType"] + " #share-buttons .module-vote-positive").html(votePositive);
    }
    else {
        $("#module-" + result["IdEducationType"] + " #share-buttons .module-vote-positive").hide();
    }
	if (voteNegative.length > 0) {
		$("#module-" + result["IdEducationType"] + " #share-buttons .module-vote-negative").show();
        $("#module-" + result["IdEducationType"] + " #share-buttons .module-vote-negative").html(voteNegative);
    }
    else {
        $("#module-" + result["IdEducationType"] + " #share-buttons .module-vote-negative").hide();
    }
}

function showNextPanelEducationTypes_module_share(result) {
    var facebook = $.trim(result["Facebook"]);
	var twitter = $.trim(result["Twitter"]);
	var live = $.trim(result["Live"]);
    if (facebook.length > 0) {
		$("#module-" + result["IdEducationType"] + " #share-buttons .facebook-button").show();
        $("#module-" + result["IdEducationType"] + " #share-buttons .facebook-button").html(facebook);
    }
    else {
        $("#module-" + result["IdEducationType"] + " #share-buttons .facebook-button").hide();
    }
	if (twitter.length > 0) {
		$("#module-" + result["IdEducationType"] + " #share-buttons .twitter-button").show();
        $("#module-" + result["IdEducationType"] + " #share-buttons .twitter-button").html(twitter);
    }
    else {
        $("#module-" + result["IdEducationType"] + " #share-buttons .twitter-button").hide();
    }
	if (live.length > 0) {
		$("#module-" + result["IdEducationType"] + " #share-buttons .live-button").show();
        $("#module-" + result["IdEducationType"] + " #share-buttons .live-button").html(live);
    }
    else {
        $("#module-" + result["IdEducationType"] + " #share-buttons .live-button").hide();
    }
}

function panelIsVisible() {
    return $("#pnlTabsModule").css("display") != "none";
}
function showNextPanelEducationTypes_onFailed(error) {
	hideUpdateProgress();
    unlock(mutex);
}

function visibilityBackPanel() {
    if (getNumControlSelected() + 1 > 0) {
        $("#ContainerBackPanels").show();
    }
    else {
        $("#ContainerBackPanels").hide();
    }
}

function LoginToTake(idEducationType, idEducationTypeSelected) {
	var params = {
			   idEducationType: idEducationType,
			   idEducationTypeSelected: idEducationTypeSelected
			 };
	CallAJAXPost("Studies/EducationDetails.aspx/LoginToTake",params , LoginToTake_onSuccess, LoginToTake_onFailed);
}

function LoginToTake_onSuccess(result) {
    HideError();
    window.location = result;
}

function LoginToTake_onFailed(error) {

}

var ctypeClick;
var examClick;
function SubscribeToETClickCT(idEducationType, idEducationTypeSelected,idContentType)
{
	ctypeClick = idContentType;
	examClick = null;
	SubscribeToET(idEducationType,idEducationTypeSelected);
}
function SubscribeToETClickExam(idEducationType, idEducationTypeSelected,idExam)
{
	ctypeClick = null;
	examClick = idExam;
	SubscribeToET(idEducationType,idEducationTypeSelected);
}

function SubscribeToET(idEducationType, idEducationTypeSelected) {
	var params = {
			   idEducationType: idEducationType,
			   idEducationTypeSelected: idEducationTypeSelected
			 };
    CallAJAXPost("Studies/EducationDetails.aspx/SubscribeToET", params, SubscribeToET_onSuccess, SubscribeToET_onFailed);
}

function SubscribeToET_onSuccess(result) {
	var urlLocation;
	if (result)
	{
		var num = parseInt(result);
		if (!isNaN(num))
		{
			urlLocation = BuildURLEducationDetail(document.location.href,ctypeClick,examClick,result);
			window.location = urlLocation;
		}
		else
		{
			showNotification(result, notificationTypes.ERROR)
		    //ShowError(result);
			disablePopup($(".popUpConfirmSubscribeToTake"));
		}
	}
    HideError();
}

function BuildURLEducationDetail(url,contentType,exam,module)
{
	var urlLocation;
	if (!ContainsQueryString(url))
	{
		 urlLocation =  url + "?o=" + module + ((contentType) ? "&ct=" + contentType : "") + ((exam) ? "&e=" + exam : "");
	}
	else
	{
		url = AddQueryStringValue(url,"o",module);
		url = AddQueryStringValue(url,"ct",contentType);
		url = AddQueryStringValue(url,"e",exam);
		urlLocation = url;
	}
	
	return urlLocation;
}

function AddQueryStringValue(url,key,value)
{
	if (ContainsQueryStringValueKey(url,key + "="))
	{
		var oldValue = getQuerystring(key,"");
		textReplace ="";
		if (value)
		{
			textReplace = key + "=" + value;
		}
		url = url.replace(key + "=" + oldValue,textReplace);
	}
	else
	{
		if (value)
		{
			url = url + "&" + key + "=" + value;
		}
	}
	
	return url;
}

function ContainsQueryStringValueKey(url,key)
{
	return url.indexOf(key) != -1;
}
function ContainsQueryString(url)
{
	return url.indexOf("?") != -1;
}

function SubscribeToET_onFailed(error) {
    ShowError(error);
    disablePopup($(".popUpConfirmSubscribeToTake"));
}


function GetListBrothers() {
    return list_brothers;
}

var list_brothers = new Array();

function redirectBlankWithPostback(ahref) {
    if (lock(mutex)) {
        if ($(ahref).attr("downloaded").toLowerCase() == "false") {
            $(ahref).attr("downloaded", "True");
            reducePendingDocuments();
        }
		winpop($(ahref).attr("url"), $(ahref).attr("target"));
		
        var list_brothers_names = new Array();
        var list_brothers_points = new Array();
		var list_brothers_levels = new Array();
		list_brothers = new Array();
        $('div[numbercontrol="' + getNumControlSelected() + '"]').find("span[this]").each(function (index) {
            list_brothers[index] = $(this).attr("this");
            list_brothers_names[index] = $(this).attr("name");
            list_brothers_points[index] = $(this).attr("points");
			list_brothers_levels[index] = $(this).attr("level");
        });

        var list = new Array(5);
        var list_lName = new Array(5);
        var list_parentIsE = new Array(5);
        var list_isLevel = new Array(5);
        var list_points = new Array(5);
		var list_levels = new Array(5);
        var idModule = parseInt($(ahref).attr("etsId")); ;
        var idETPrincipal = parseInt($(ahref).attr("etId"));
        addEt(idModule, 0, list, 0, idETPrincipal, list_lName, list_parentIsE, list_isLevel, list_points, list_levels);
        var culture = $('input[id$="hfCulture"]').attr("value");
		var params = {
			   idContentType: parseInt($(ahref).attr("ctId")),
			   idEducationTypeSelected: idModule,
			   idEducationType: idETPrincipal,
			   parentIDList: list,
			   nameList: list_lName,
			   pointList: list_points,
			   levelList: list_levels,
			   isParentEnabledList: list_parentIsE,
			   isLevel: list_isLevel,
			   isApproved: isApproved(),
			   pendingDocuments: getPendingDocuments(),
			   culture: culture.toString(),
			   list_brothers: list_brothers,
			   list_brothers_names: list_brothers_names,
			   list_brothers_points: list_brothers_points,
			   list_brothers_levels: list_brothers_levels
			 };
			 
		CallAJAXPost("Studies/EducationDetails.aspx/DownloadContent", params, DownloadContent_onSuccess, DownloadContent_onFailed);
	}
}

function addEt(idET, idLevel, list, count, etFinal, list_lName, list_parentIsE, list_isLevel, list_points, list_levels) {
    if (idLevel > 1) {
        var el = $('span.elevel[this="' + idLevel + '"][parent="' + idET + '"]');
        list_parentIsE[count] = el.attr("parentIsE");
        list[count] = idLevel;
        list_isLevel[count] = true;
        list_lName[count++] = el.attr("name");
    }

    if (idET != etFinal) {        
        var et = $('span.etype[this="' + idET + '"]')
        list[count] = idET;
        list_parentIsE[count] = et.attr("parentIsE");
        list_points[count] = et.attr("points");
		list_levels[count] = et.attr("level");
        list_isLevel[count] = false;
        list_lName[count++] = et.attr("name");
                
        var idETn = parseInt(et.attr("parent"));
        var idLeveln = parseInt(et.attr("parentlevel"));

        addEt(idETn, idLeveln, list, count, etFinal, list_lName, list_parentIsE, list_isLevel, list_points, list_levels);   
    }
}

function RefreshProgressBars(result, idET, idETFinal, idLevel) {
    if (idLevel > 1) {
        var html = result["et:" + idET + "|el:" + idLevel];
        if (html) {
            $('span.elevel[this="' + idLevel + '"][parent="' + idET + '"]').html(html);
        }
    }
    var html = result["et:" + idET];
    var et = $('span.etype[this="' + idET + '"]');
    if (html) {
        et.html(html);
    }
    if (idET != idETFinal) {
        RefreshProgressBars(result, parseInt(et.attr("parent")), idETFinal, parseInt(et.attr("parentLevel")));
    }
 
}
function DownloadContent_onSuccess(result) {
    HideError();
    $('div[ctid="' + result["Download"] + '"]').attr("class", $('*[ctid="' + result["Download"] + '"]').attr("class") + " module-material-downloaded");
    RefreshProgressBars(result, parseInt(result["Module"]), parseInt(result["IdEducationTypePrincipal"]), 0);

    if (result["NumControl"]) {
        nextControl = $('div[numbercontrol="' + result["NumControl"] + '"]');

        if ($(nextControl).attr("numbercontrol")) {
                var brothers = GetListBrothers();
                for (i = 0; i < brothers.length; i++) {
                    etControl = $(nextControl).find('span[this="' + brothers[i] + '"]')
                    etControl.html(result["et:" + brothers[i]]);
                    //$(nextControl).replaceWith(result["ModuleList"]);
                    if (brothers[i] == parseInt(result["Module"])) {
                        etControl.find(".progress_name_icon").attr("class", "progress_name_icon");
                    }
                    
            }
        }
        
    }
	
	
	if (result["HtmlResponseExams"]) {
		
		var controlModule = $("#module-" + result["IdEducationType"]);
		
		if (result["ShowSupplementaryMaterials"].toLowerCase() == "false")
		{
			controlModule.find('.module-exams-title').show();
			controlModule.find('#pnlExam').html(result["HtmlResponseExams"]);
		}
		else
		{
			controlModule.find('.module-exams-title').hide();
			controlModule.find('#pnlExam').html("");
			if (result["CountSupplementaryMaterials"] != "0")
			{
				controlModule.find('.module-supplementary-materials-title').show();
				controlModule.find('#pnlSuppelementaryMaterials').html(result["HTMLResponseSupplementaryMaterials"]);
			}
			else
			{
				
				controlModule.find('.module-supplementary-materials-title').hide();
			}
		}
		
	}
	
    RefreshPrincipalProgress(result);
    BindConfirmationPopup();

    unlock(mutex);
}

function RefreshPrincipalProgress(result) {
    var progress = result["PercentageProgress"]
    controlPrincipal = $('div[id$="control_percentage_principal"]');
    controlPrincipal.css("width", (progress + "%"));
    $("#number_percentage_principal").find("span").html(progress);
    if (parseInt(progress) == 100) {
        controlPrincipal.parent().attr("class", "control_progress_principal completed");
    }

}
function DownloadContent_onFailed(error) {


    unlock(mutex);
}


function ShowError(message) {
    $('span[id$="lblErrorWebMethods"]').show();
    $('span[id$="lblErrorWebMethods"]').html(message);
}

function HideError() {
    $('span[id$="lblErrorWebMethods"]').hide();
}


//EXAMS
function nextQuestion() {
    setVisibilityToRequiredAnswerMessage(false);

    var questionDiscriminator = $('input[id$="hfQuestionDiscriminator"]');

    switch (questionDiscriminator.attr("value")) {
        case "1": //TrueFalseQuestion
            var answer = $('input[name=rbTrueFalse]:radio:checked').attr("value");
            break;

        case "2": //SingleChoiceQuestion
            var answer = $('input[name=rbAnswer]:radio:checked').attr("value");
            break;

        case "3": //MultipleChoiceQuestion
            var cbAnswers = $('input[name=cbAnswer]:checkbox:checked');
            var answer = new Array();
            cbAnswers.each(function(index) {
                answer.push($(this).attr("value"));
            });
            break;
		case "4": //FixedMultipleChoiceQuestion
			var cbAnswers = $('input[name=cbAnswer]:checkbox:checked');
            var answer = new Array();
            cbAnswers.each(function(index) {
                answer.push($(this).attr("value"));
            });
    }
    if (!validateSelectedAnswer(answer))
        return false;

	if (questionDiscriminator.attr("value") == "4" && !ValidateAnswersNumbers(answer))
		return false;
		
    postAnswer(answer);
}

function ValidateAnswersNumbers(answer)
{
	var number = parseInt($("#hfFixedMultipleChoiceQuestionsAnswers").val());
	if (answer.length != number)
	{
		$("#msgRequiredAnswer").html($("#messageFixedMultipleChoiceQuestionsAnswers").html());
		$("#msgRequiredAnswer").css({ visibility: "visible" });
		return false;
	}
	else
	{
		$("#msgRequiredAnswer").css({ visibility: "hidden" });
		return true;
	}
	
}

function validateSelectedAnswer(answer) {
    if (answer && answer.length > 0) {
        // answer is valid
        return true;
    }
    // answer is not valid
    setVisibilityToRequiredAnswerMessage(true)
    return false;
}

function setVisibilityToRequiredAnswerMessage(visible) {
    if (visible)
	{
		$("#msgRequiredAnswer").html($("#RequireAnswerText").html());
        $("#msgRequiredAnswer").css({ visibility: "visible" });
		$("#msgRequiredAnswer").show();
	}
    else
        $("#msgRequiredAnswer").css({ visibility: "hidden" });
}

function postAnswer(answer) {
    if (answer == undefined) answer = null;
    culture = $('input[id$="hfCulture"]').attr("value");
    idET = $('input[id$="hfIdEducationType"]').attr("value");
	var params = {
			   answer: answer,
			   culture: culture,
			   idET: idET
			 };
	CallAJAXPost("Studies/TakeExam.aspx/NextQuestion", params, nextQuestion_SuccessHandler, nextQuestion_ErrorHandler);
    showUpdateProgress($("#lnkContinue"));
}

function nextQuestion_SuccessHandler(result) {
    if (result["Status"] == "NextQuestion") {
        $('input[id$="hfQuestionDiscriminator"]').attr("value", result["QuestionDiscriminator"]);
        $('#questionText').html(result["QuestionText"]);
        $('#answer_container').html(result["PossibleAnswersHTML"]);
	
		var currentQuestion = parseInt($('input[id$="hfCurrentQuestion"]').attr("value"));
		var questionQty = parseInt($('input[id$="hfQuestionQty"]').attr("value"));
		
		if(currentQuestion != questionQty){
			$('input[id$="hfCurrentQuestion"]').attr("value", parseInt(currentQuestion)+1);
			refreshQuestionNumber();
		}
		
        SetStyleInCheckAndRadioButtons();
    }
    else {
        // TimeOver || Approved || Fail || Error || other...
        finishExam(result["Message"], result["Badges"], result["Facebook"], result["Twitter"]);
        if (result["Status"] == "Approved") {
			$("#share-buttons").show();
            $("#trShareButtons").show();
            $("#lnkTryAgainExam").hide();		
			if (result["ShowAnswerReview"] == "False") {				    
				$(".whattodo #answerReview").hide();				    
			}
            if (result["Approved"] == "true") {
                $("#messageCompletedEducationType").show();
				$("#msjPassModule").hide();
				$("#msjPassCourse").show();		
            }
            else {
                $("#messageCompletedEducationType").hide();
				$("#msjPassModule").show();
				$("#msjPassCourse").hide();
            }
        }
    }
	BindCustomCheckBox();
    hideUpdateProgress();
}

function loadCarousel(){
	$("#mycarousel").jcarousel({
		scroll: 1,
		initCallback: carousel_initCallback
	});
}

function carousel_initCallback(carousel, state) {
    if (state == 'init'){
		$(".jcarousel-skin-tango2").fadeIn();
		$('#mycarousel').jcarousel({scroll: 1});
	}
}

function nextQuestion_ErrorHandler(error) {
    finishExam();
}

function finishExam(message, badges, facebook, twitter) {
    finishExamTimer();

    // load popup message
    if (message != undefined)
        $("#finalizedExamMessage").html(message);
	
	// load popup badges
    if (badges != undefined)
        $("#finalizedExamBadges").html(badges);
			
	// load facebook status button
    if (facebook != undefined)
        $("#facebook-status").html(facebook);
			
	// load twitter status button
    if (twitter != undefined)
        $("#twitter-status").html(twitter);
    
    showPopup("popUpFinalizedExam");
}


/*** EDUCATION TYPE VOTE ***/

function educationTypeVote(button) {
    var jbutton = $(button);
    if (!jbutton.hasClass("et-vote-disabled")) {

        var isPositive = jbutton.hasClass("et-vote-positive");
        var idEducationType = jbutton.attr("ideducationtype");
        culture = $('input[id$="hfCulture"]').attr("value");
		var params = {
			   idEducationType: idEducationType,
			   isPositive: isPositive,
			   culture: culture
			 };
		CallAJAXPost("Studies/EducationDetails.aspx/Vote", params, educationTypeVote_SuccessHandler, educationTypeVote_ErrorHandler);
        // update every vote controls status for the education type id
        
        // select vote button
        var selectedButtonClass = "et-vote-" + (isPositive ? "positive" : "negative");
        $("[ideducationtype='" + idEducationType + "']." + selectedButtonClass).addClass("et-vote-disabled et-vote-selected");
        // increment counter
        var selectedCounterClass = selectedButtonClass + "-counter";
        var counter = parseInt($("[ideducationtype='" + idEducationType + "']." + selectedCounterClass).html());
        $("[ideducationtype='" + idEducationType + "']." + selectedCounterClass).html(counter + 1);
        // disable the other group button
        var notSelectedButtonClass = "et-vote-" + (isPositive ? "negative" : "positive");
        $("[ideducationtype='" + idEducationType + "']." + notSelectedButtonClass).addClass("et-vote-disabled");
    }
}
function educationTypeVote_SuccessHandler(result) {
    if (result["Status"] == "Error") {
        showNotification(result["Message"], "error");
    }
}
function educationTypeVote_ErrorHandler(error) {
}

/* Get Querystring Value */
function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function winpop(url,target){
var w = screen.width;
var h = screen.height;
window.open(url,target,'left=0,top=0,width='+w+',height='+h+',fullscreen=1,toolbar=1,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,status=1,titlebar=1');
}

function ShowTopTen() {
    $("#toptenglobal").toggleClass("hide");
    $("#toptenlocal").toggleClass("hide");
    $("#sb_topten .option").toggleClass("active");
}

function ShowActivity() {
    $("div[id$='totalactivityGlobal']").toggleClass("hide");
    $("div[id$='totalactivityLocal']").toggleClass("hide");
    $("#sb_communityinfo .option").toggleClass("active");
}



/*!
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function(g){var q={vertical:!1,rtl:!1,start:1,offset:1,size:null,scroll:3,visible:null,animation:"normal",easing:"swing",auto:0,wrap:null,initCallback:null,setupCallback:null,reloadCallback:null,itemLoadCallback:null,itemFirstInCallback:null,itemFirstOutCallback:null,itemLastInCallback:null,itemLastOutCallback:null,itemVisibleInCallback:null,itemVisibleOutCallback:null,animationStepCallback:null,buttonNextHTML:"<div></div>",buttonPrevHTML:"<div></div>",buttonNextEvent:"click",buttonPrevEvent:"click", buttonNextCallback:null,buttonPrevCallback:null,itemFallbackDimension:null},m=!1;g(window).bind("load.jcarousel",function(){m=!0});g.jcarousel=function(a,c){this.options=g.extend({},q,c||{});this.autoStopped=this.locked=!1;this.buttonPrevState=this.buttonNextState=this.buttonPrev=this.buttonNext=this.list=this.clip=this.container=null;if(!c||c.rtl===void 0)this.options.rtl=(g(a).attr("dir")||g("html").attr("dir")||"").toLowerCase()=="rtl";this.wh=!this.options.vertical?"width":"height";this.lt=!this.options.vertical? this.options.rtl?"right":"left":"top";for(var b="",d=a.className.split(" "),f=0;f<d.length;f++)if(d[f].indexOf("jcarousel-skin")!=-1){g(a).removeClass(d[f]);b=d[f];break}a.nodeName.toUpperCase()=="UL"||a.nodeName.toUpperCase()=="OL"?(this.list=g(a),this.clip=this.list.parents(".jcarousel-clip"),this.container=this.list.parents(".jcarousel-container")):(this.container=g(a),this.list=this.container.find("ul,ol").eq(0),this.clip=this.container.find(".jcarousel-clip"));if(this.clip.size()===0)this.clip= this.list.wrap("<div></div>").parent();if(this.container.size()===0)this.container=this.clip.wrap("<div></div>").parent();b!==""&&this.container.parent()[0].className.indexOf("jcarousel-skin")==-1&&this.container.wrap('<div class=" '+b+'"></div>');this.buttonPrev=g(".jcarousel-prev",this.container);if(this.buttonPrev.size()===0&&this.options.buttonPrevHTML!==null)this.buttonPrev=g(this.options.buttonPrevHTML).appendTo(this.container);this.buttonPrev.addClass(this.className("jcarousel-prev"));this.buttonNext= g(".jcarousel-next",this.container);if(this.buttonNext.size()===0&&this.options.buttonNextHTML!==null)this.buttonNext=g(this.options.buttonNextHTML).appendTo(this.container);this.buttonNext.addClass(this.className("jcarousel-next"));this.clip.addClass(this.className("jcarousel-clip")).css({position:"relative"});this.list.addClass(this.className("jcarousel-list")).css({overflow:"hidden",position:"relative",top:0,margin:0,padding:0}).css(this.options.rtl?"right":"left",0);this.container.addClass(this.className("jcarousel-container")).css({position:"relative"}); !this.options.vertical&&this.options.rtl&&this.container.addClass("jcarousel-direction-rtl").attr("dir","rtl");var j=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible):null,b=this.list.children("li"),e=this;if(b.size()>0){var h=0,i=this.options.offset;b.each(function(){e.format(this,i++);h+=e.dimension(this,j)});this.list.css(this.wh,h+100+"px");if(!c||c.size===void 0)this.options.size=b.size()}this.container.css("display","block");this.buttonNext.css("display","block");this.buttonPrev.css("display", "block");this.funcNext=function(){e.next()};this.funcPrev=function(){e.prev()};this.funcResize=function(){e.resizeTimer&&clearTimeout(e.resizeTimer);e.resizeTimer=setTimeout(function(){e.reload()},100)};this.options.initCallback!==null&&this.options.initCallback(this,"init");!m&&g.browser.safari?(this.buttons(!1,!1),g(window).bind("load.jcarousel",function(){e.setup()})):this.setup()};var f=g.jcarousel;f.fn=f.prototype={jcarousel:"0.2.8"};f.fn.extend=f.extend=g.extend;f.fn.extend({setup:function(){this.prevLast= this.prevFirst=this.last=this.first=null;this.animating=!1;this.tail=this.resizeTimer=this.timer=null;this.inTail=!1;if(!this.locked){this.list.css(this.lt,this.pos(this.options.offset)+"px");var a=this.pos(this.options.start,!0);this.prevFirst=this.prevLast=null;this.animate(a,!1);g(window).unbind("resize.jcarousel",this.funcResize).bind("resize.jcarousel",this.funcResize);this.options.setupCallback!==null&&this.options.setupCallback(this)}},reset:function(){this.list.empty();this.list.css(this.lt, "0px");this.list.css(this.wh,"10px");this.options.initCallback!==null&&this.options.initCallback(this,"reset");this.setup()},reload:function(){this.tail!==null&&this.inTail&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+this.tail);this.tail=null;this.inTail=!1;this.options.reloadCallback!==null&&this.options.reloadCallback(this);if(this.options.visible!==null){var a=this,c=Math.ceil(this.clipping()/this.options.visible),b=0,d=0;this.list.children("li").each(function(f){b+=a.dimension(this, c);f+1<a.first&&(d=b)});this.list.css(this.wh,b+"px");this.list.css(this.lt,-d+"px")}this.scroll(this.first,!1)},lock:function(){this.locked=!0;this.buttons()},unlock:function(){this.locked=!1;this.buttons()},size:function(a){if(a!==void 0)this.options.size=a,this.locked||this.buttons();return this.options.size},has:function(a,c){if(c===void 0||!c)c=a;if(this.options.size!==null&&c>this.options.size)c=this.options.size;for(var b=a;b<=c;b++){var d=this.get(b);if(!d.length||d.hasClass("jcarousel-item-placeholder"))return!1}return!0}, get:function(a){return g(">.jcarousel-item-"+a,this.list)},add:function(a,c){var b=this.get(a),d=0,p=g(c);if(b.length===0)for(var j,e=f.intval(a),b=this.create(a);;){if(j=this.get(--e),e<=0||j.length){e<=0?this.list.prepend(b):j.after(b);break}}else d=this.dimension(b);p.get(0).nodeName.toUpperCase()=="LI"?(b.replaceWith(p),b=p):b.empty().append(c);this.format(b.removeClass(this.className("jcarousel-item-placeholder")),a);p=this.options.visible!==null?Math.ceil(this.clipping()/this.options.visible): null;d=this.dimension(b,p)-d;a>0&&a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))-d+"px");this.list.css(this.wh,f.intval(this.list.css(this.wh))+d+"px");return b},remove:function(a){var c=this.get(a);if(c.length&&!(a>=this.first&&a<=this.last)){var b=this.dimension(c);a<this.first&&this.list.css(this.lt,f.intval(this.list.css(this.lt))+b+"px");c.remove();this.list.css(this.wh,f.intval(this.list.css(this.wh))-b+"px")}},next:function(){this.tail!==null&&!this.inTail?this.scrollTail(!1): this.scroll((this.options.wrap=="both"||this.options.wrap=="last")&&this.options.size!==null&&this.last==this.options.size?1:this.first+this.options.scroll)},prev:function(){this.tail!==null&&this.inTail?this.scrollTail(!0):this.scroll((this.options.wrap=="both"||this.options.wrap=="first")&&this.options.size!==null&&this.first==1?this.options.size:this.first-this.options.scroll)},scrollTail:function(a){if(!this.locked&&!this.animating&&this.tail){this.pauseAuto();var c=f.intval(this.list.css(this.lt)), c=!a?c-this.tail:c+this.tail;this.inTail=!a;this.prevFirst=this.first;this.prevLast=this.last;this.animate(c)}},scroll:function(a,c){!this.locked&&!this.animating&&(this.pauseAuto(),this.animate(this.pos(a),c))},pos:function(a,c){var b=f.intval(this.list.css(this.lt));if(this.locked||this.animating)return b;this.options.wrap!="circular"&&(a=a<1?1:this.options.size&&a>this.options.size?this.options.size:a);for(var d=this.first>a,g=this.options.wrap!="circular"&&this.first<=1?1:this.first,j=d?this.get(g): this.get(this.last),e=d?g:g-1,h=null,i=0,k=!1,l=0;d?--e>=a:++e<a;){h=this.get(e);k=!h.length;if(h.length===0&&(h=this.create(e).addClass(this.className("jcarousel-item-placeholder")),j[d?"before":"after"](h),this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size)))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)));j=h;l=this.dimension(h);k&&(i+=l);if(this.first!==null&&(this.options.wrap=="circular"||e>=1&&(this.options.size===null||e<= this.options.size)))b=d?b+l:b-l}for(var g=this.clipping(),m=[],o=0,n=0,j=this.get(a-1),e=a;++o;){h=this.get(e);k=!h.length;if(h.length===0){h=this.create(e).addClass(this.className("jcarousel-item-placeholder"));if(j.length===0)this.list.prepend(h);else j[d?"before":"after"](h);if(this.first!==null&&this.options.wrap=="circular"&&this.options.size!==null&&(e<=0||e>this.options.size))j=this.get(this.index(e)),j.length&&(h=this.add(e,j.clone(!0)))}j=h;l=this.dimension(h);if(l===0)throw Error("jCarousel: No width/height set for items. This will cause an infinite loop. Aborting..."); this.options.wrap!="circular"&&this.options.size!==null&&e>this.options.size?m.push(h):k&&(i+=l);n+=l;if(n>=g)break;e++}for(h=0;h<m.length;h++)m[h].remove();i>0&&(this.list.css(this.wh,this.dimension(this.list)+i+"px"),d&&(b-=i,this.list.css(this.lt,f.intval(this.list.css(this.lt))-i+"px")));i=a+o-1;if(this.options.wrap!="circular"&&this.options.size&&i>this.options.size)i=this.options.size;if(e>i){o=0;e=i;for(n=0;++o;){h=this.get(e--);if(!h.length)break;n+=this.dimension(h);if(n>=g)break}}e=i-o+ 1;this.options.wrap!="circular"&&e<1&&(e=1);if(this.inTail&&d)b+=this.tail,this.inTail=!1;this.tail=null;if(this.options.wrap!="circular"&&i==this.options.size&&i-o+1>=1&&(d=f.intval(this.get(i).css(!this.options.vertical?"marginRight":"marginBottom")),n-d>g))this.tail=n-g-d;if(c&&a===this.options.size&&this.tail)b-=this.tail,this.inTail=!0;for(;a-- >e;)b+=this.dimension(this.get(a));this.prevFirst=this.first;this.prevLast=this.last;this.first=e;this.last=i;return b},animate:function(a,c){if(!this.locked&& !this.animating){this.animating=!0;var b=this,d=function(){b.animating=!1;a===0&&b.list.css(b.lt,0);!b.autoStopped&&(b.options.wrap=="circular"||b.options.wrap=="both"||b.options.wrap=="last"||b.options.size===null||b.last<b.options.size||b.last==b.options.size&&b.tail!==null&&!b.inTail)&&b.startAuto();b.buttons();b.notify("onAfterAnimation");if(b.options.wrap=="circular"&&b.options.size!==null)for(var c=b.prevFirst;c<=b.prevLast;c++)c!==null&&!(c>=b.first&&c<=b.last)&&(c<1||c>b.options.size)&&b.remove(c)}; this.notify("onBeforeAnimation");if(!this.options.animation||c===!1)this.list.css(this.lt,a+"px"),d();else{var f=!this.options.vertical?this.options.rtl?{right:a}:{left:a}:{top:a},d={duration:this.options.animation,easing:this.options.easing,complete:d};if(g.isFunction(this.options.animationStepCallback))d.step=this.options.animationStepCallback;this.list.animate(f,d)}}},startAuto:function(a){if(a!==void 0)this.options.auto=a;if(this.options.auto===0)return this.stopAuto();if(this.timer===null){this.autoStopped= !1;var c=this;this.timer=window.setTimeout(function(){c.next()},this.options.auto*1E3)}},stopAuto:function(){this.pauseAuto();this.autoStopped=!0},pauseAuto:function(){if(this.timer!==null)window.clearTimeout(this.timer),this.timer=null},buttons:function(a,c){if(a==null&&(a=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="first"||this.options.size===null||this.last<this.options.size),!this.locked&&(!this.options.wrap||this.options.wrap=="first")&&this.options.size!==null&& this.last>=this.options.size))a=this.tail!==null&&!this.inTail;if(c==null&&(c=!this.locked&&this.options.size!==0&&(this.options.wrap&&this.options.wrap!="last"||this.first>1),!this.locked&&(!this.options.wrap||this.options.wrap=="last")&&this.options.size!==null&&this.first==1))c=this.tail!==null&&this.inTail;var b=this;this.buttonNext.size()>0?(this.buttonNext.unbind(this.options.buttonNextEvent+".jcarousel",this.funcNext),a&&this.buttonNext.bind(this.options.buttonNextEvent+".jcarousel",this.funcNext), this.buttonNext[a?"removeClass":"addClass"](this.className("jcarousel-next-disabled")).attr("disabled",a?!1:!0),this.options.buttonNextCallback!==null&&this.buttonNext.data("jcarouselstate")!=a&&this.buttonNext.each(function(){b.options.buttonNextCallback(b,this,a)}).data("jcarouselstate",a)):this.options.buttonNextCallback!==null&&this.buttonNextState!=a&&this.options.buttonNextCallback(b,null,a);this.buttonPrev.size()>0?(this.buttonPrev.unbind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev), c&&this.buttonPrev.bind(this.options.buttonPrevEvent+".jcarousel",this.funcPrev),this.buttonPrev[c?"removeClass":"addClass"](this.className("jcarousel-prev-disabled")).attr("disabled",c?!1:!0),this.options.buttonPrevCallback!==null&&this.buttonPrev.data("jcarouselstate")!=c&&this.buttonPrev.each(function(){b.options.buttonPrevCallback(b,this,c)}).data("jcarouselstate",c)):this.options.buttonPrevCallback!==null&&this.buttonPrevState!=c&&this.options.buttonPrevCallback(b,null,c);this.buttonNextState= a;this.buttonPrevState=c},notify:function(a){var c=this.prevFirst===null?"init":this.prevFirst<this.first?"next":"prev";this.callback("itemLoadCallback",a,c);this.prevFirst!==this.first&&(this.callback("itemFirstInCallback",a,c,this.first),this.callback("itemFirstOutCallback",a,c,this.prevFirst));this.prevLast!==this.last&&(this.callback("itemLastInCallback",a,c,this.last),this.callback("itemLastOutCallback",a,c,this.prevLast));this.callback("itemVisibleInCallback",a,c,this.first,this.last,this.prevFirst, this.prevLast);this.callback("itemVisibleOutCallback",a,c,this.prevFirst,this.prevLast,this.first,this.last)},callback:function(a,c,b,d,f,j,e){if(!(this.options[a]==null||typeof this.options[a]!="object"&&c!="onAfterAnimation")){var h=typeof this.options[a]=="object"?this.options[a][c]:this.options[a];if(g.isFunction(h)){var i=this;if(d===void 0)h(i,b,c);else if(f===void 0)this.get(d).each(function(){h(i,this,d,b,c)});else for(var a=function(a){i.get(a).each(function(){h(i,this,a,b,c)})},k=d;k<=f;k++)k!== null&&!(k>=j&&k<=e)&&a(k)}}},create:function(a){return this.format("<li></li>",a)},format:function(a,c){for(var a=g(a),b=a.get(0).className.split(" "),d=0;d<b.length;d++)b[d].indexOf("jcarousel-")!=-1&&a.removeClass(b[d]);a.addClass(this.className("jcarousel-item")).addClass(this.className("jcarousel-item-"+c)).css({"float":this.options.rtl?"right":"left","list-style":"none"}).attr("jcarouselindex",c);return a},className:function(a){return a+" "+a+(!this.options.vertical?"-horizontal":"-vertical")}, dimension:function(a,c){var b=g(a);if(c==null)return!this.options.vertical?b.outerWidth(!0)||f.intval(this.options.itemFallbackDimension):b.outerHeight(!0)||f.intval(this.options.itemFallbackDimension);else{var d=!this.options.vertical?c-f.intval(b.css("marginLeft"))-f.intval(b.css("marginRight")):c-f.intval(b.css("marginTop"))-f.intval(b.css("marginBottom"));g(b).css(this.wh,d+"px");return this.dimension(b)}},clipping:function(){return!this.options.vertical?this.clip[0].offsetWidth-f.intval(this.clip.css("borderLeftWidth"))- f.intval(this.clip.css("borderRightWidth")):this.clip[0].offsetHeight-f.intval(this.clip.css("borderTopWidth"))-f.intval(this.clip.css("borderBottomWidth"))},index:function(a,c){if(c==null)c=this.options.size;return Math.round(((a-1)/c-Math.floor((a-1)/c))*c)+1}});f.extend({defaults:function(a){return g.extend(q,a||{})},intval:function(a){a=parseInt(a,10);return isNaN(a)?0:a},windowLoaded:function(){m=!0}});g.fn.jcarousel=function(a){if(typeof a=="string"){var c=g(this).data("jcarousel"),b=Array.prototype.slice.call(arguments, 1);return c[a].apply(c,b)}else return this.each(function(){var b=g(this).data("jcarousel");b?(a&&g.extend(b.options,a),b.reload()):g(this).data("jcarousel",new f(this,a))})}})(jQuery);

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*JQUERY UI*/

    /*!
    * jQuery UI 1.8.6
    *
    * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
    * Dual licensed under the MIT or GPL Version 2 licenses.
    * http://jquery.org/license
    *
    * http://docs.jquery.com/UI
    */
    (function(c, j) {
        function k(a) { return !c(a).parents().andSelf().filter(function() { return c.curCSS(this, "visibility") === "hidden" || c.expr.filters.hidden(this) }).length } c.ui = c.ui || {}; if (!c.ui.version) {
            c.extend(c.ui, { version: "1.8.6", keyCode: { ALT: 18, BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, COMMAND: 91, COMMAND_LEFT: 91, COMMAND_RIGHT: 93, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, MENU: 93, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106,
                NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38, WINDOWS: 91}
            }); c.fn.extend({ _focus: c.fn.focus, focus: function(a, b) { return typeof a === "number" ? this.each(function() { var d = this; setTimeout(function() { c(d).focus(); b && b.call(d) }, a) }) : this._focus.apply(this, arguments) }, scrollParent: function() {
                var a; a = c.browser.msie && /(static|relative)/.test(this.css("position")) || /absolute/.test(this.css("position")) ? this.parents().filter(function() {
                    return /(relative|absolute|fixed)/.test(c.curCSS(this,
"position", 1)) && /(auto|scroll)/.test(c.curCSS(this, "overflow", 1) + c.curCSS(this, "overflow-y", 1) + c.curCSS(this, "overflow-x", 1))
                }).eq(0) : this.parents().filter(function() { return /(auto|scroll)/.test(c.curCSS(this, "overflow", 1) + c.curCSS(this, "overflow-y", 1) + c.curCSS(this, "overflow-x", 1)) }).eq(0); return /fixed/.test(this.css("position")) || !a.length ? c(document) : a
            }, zIndex: function(a) {
                if (a !== j) return this.css("zIndex", a); if (this.length) {
                    a = c(this[0]); for (var b; a.length && a[0] !== document; ) {
                        b = a.css("position");
                        if (b === "absolute" || b === "relative" || b === "fixed") { b = parseInt(a.css("zIndex"), 10); if (!isNaN(b) && b !== 0) return b } a = a.parent()
                    } 
                } return 0
            }, disableSelection: function() { return this.bind((c.support.selectstart ? "selectstart" : "mousedown") + ".ui-disableSelection", function(a) { a.preventDefault() }) }, enableSelection: function() { return this.unbind(".ui-disableSelection") } 
            }); c.each(["Width", "Height"], function(a, b) {
                function d(f, g, l, m) {
                    c.each(e, function() {
                        g -= parseFloat(c.curCSS(f, "padding" + this, true)) || 0; if (l) g -= parseFloat(c.curCSS(f,
"border" + this + "Width", true)) || 0; if (m) g -= parseFloat(c.curCSS(f, "margin" + this, true)) || 0
                    }); return g
                } var e = b === "Width" ? ["Left", "Right"] : ["Top", "Bottom"], h = b.toLowerCase(), i = { innerWidth: c.fn.innerWidth, innerHeight: c.fn.innerHeight, outerWidth: c.fn.outerWidth, outerHeight: c.fn.outerHeight }; c.fn["inner" + b] = function(f) { if (f === j) return i["inner" + b].call(this); return this.each(function() { c(this).css(h, d(this, f) + "px") }) }; c.fn["outer" + b] = function(f, g) {
                    if (typeof f !== "number") return i["outer" + b].call(this, f); return this.each(function() {
                        c(this).css(h,
d(this, f, true, g) + "px")
                    })
                } 
            }); c.extend(c.expr[":"], { data: function(a, b, d) { return !!c.data(a, d[3]) }, focusable: function(a) { var b = a.nodeName.toLowerCase(), d = c.attr(a, "tabindex"); if ("area" === b) { b = a.parentNode; d = b.name; if (!a.href || !d || b.nodeName.toLowerCase() !== "map") return false; a = c("img[usemap=#" + d + "]")[0]; return !!a && k(a) } return (/input|select|textarea|button|object/.test(b) ? !a.disabled : "a" == b ? a.href || !isNaN(d) : !isNaN(d)) && k(a) }, tabbable: function(a) { var b = c.attr(a, "tabindex"); return (isNaN(b) || b >= 0) && c(a).is(":focusable") } });
            c(function() { var a = document.body, b = a.appendChild(b = document.createElement("div")); c.extend(b.style, { minHeight: "100px", height: "auto", padding: 0, borderWidth: 0 }); c.support.minHeight = b.offsetHeight === 100; c.support.selectstart = "onselectstart" in b; a.removeChild(b).style.display = "none" }); c.extend(c.ui, { plugin: { add: function(a, b, d) { a = c.ui[a].prototype; for (var e in d) { a.plugins[e] = a.plugins[e] || []; a.plugins[e].push([b, d[e]]) } }, call: function(a, b, d) {
                if ((b = a.plugins[b]) && a.element[0].parentNode) for (var e = 0; e < b.length; e++) a.options[b[e][0]] &&
b[e][1].apply(a.element, d)
            } 
            }, contains: function(a, b) { return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b) }, hasScroll: function(a, b) { if (c(a).css("overflow") === "hidden") return false; b = b && b === "left" ? "scrollLeft" : "scrollTop"; var d = false; if (a[b] > 0) return true; a[b] = 1; d = a[b] > 0; a[b] = 0; return d }, isOverAxis: function(a, b, d) { return a > b && a < b + d }, isOver: function(a, b, d, e, h, i) { return c.ui.isOverAxis(a, d, h) && c.ui.isOverAxis(b, e, i) } 
            })
        } 
    })(jQuery);
    ; /*
 * jQuery UI Datepicker 1.8.6
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Datepicker
 *
 * Depends:
 *	jquery.ui.core.js
 */
    (function(d, G) {
        function K() {
            this.debug = false; this._curInst = null; this._keyEvent = false; this._disabledInputs = []; this._inDialog = this._datepickerShowing = false; this._mainDivId = "ui-datepicker-div"; this._inlineClass = "ui-datepicker-inline"; this._appendClass = "ui-datepicker-append"; this._triggerClass = "ui-datepicker-trigger"; this._dialogClass = "ui-datepicker-dialog"; this._disableClass = "ui-datepicker-disabled"; this._unselectableClass = "ui-datepicker-unselectable"; this._currentClass = "ui-datepicker-current-day"; this._dayOverClass =
"ui-datepicker-days-cell-over"; this.regional = []; this.regional[""] = { closeText: "Done", prevText: "Prev", nextText: "Next", currentText: "Today", monthNames: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthNamesShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], dayNamesMin: ["Su",
"Mo", "Tu", "We", "Th", "Fr", "Sa"], weekHeader: "Wk", dateFormat: "mm/dd/yy", firstDay: 0, isRTL: false, showMonthAfterYear: false, yearSuffix: ""
}; this._defaults = { showOn: "focus", showAnim: "fadeIn", showOptions: {}, defaultDate: null, appendText: "", buttonText: "...", buttonImage: "", buttonImageOnly: false, hideIfNoPrevNext: false, navigationAsDateFormat: false, gotoCurrent: false, changeMonth: false, changeYear: false, yearRange: "c-10:c+10", showOtherMonths: false, selectOtherMonths: false, showWeek: false, calculateWeek: this.iso8601Week, shortYearCutoff: "+10",
    minDate: null, maxDate: null, duration: "fast", beforeShowDay: null, beforeShow: null, onSelect: null, onChangeMonthYear: null, onClose: null, numberOfMonths: 1, showCurrentAtPos: 0, stepMonths: 1, stepBigMonths: 12, altField: "", altFormat: "", constrainInput: true, showButtonPanel: false, autoSize: false
}; d.extend(this._defaults, this.regional[""]); this.dpDiv = d('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')
        } function E(a, b) {
            d.extend(a,
b); for (var c in b) if (b[c] == null || b[c] == G) a[c] = b[c]; return a
        } d.extend(d.ui, { datepicker: { version: "1.8.6"} }); var y = (new Date).getTime(); d.extend(K.prototype, { markerClassName: "hasDatepicker", log: function() { this.debug && console.log.apply("", arguments) }, _widgetDatepicker: function() { return this.dpDiv }, setDefaults: function(a) { E(this._defaults, a || {}); return this }, _attachDatepicker: function(a, b) {
            var c = null; for (var e in this._defaults) {
                var f = a.getAttribute("date:" + e); if (f) {
                    c = c || {}; try { c[e] = eval(f) } catch (h) {
                        c[e] =
f
                    } 
                } 
            } e = a.nodeName.toLowerCase(); f = e == "div" || e == "span"; if (!a.id) { this.uuid += 1; a.id = "dp" + this.uuid } var i = this._newInst(d(a), f); i.settings = d.extend({}, b || {}, c || {}); if (e == "input") this._connectDatepicker(a, i); else f && this._inlineDatepicker(a, i)
        }, _newInst: function(a, b) { return { id: a[0].id.replace(/([^A-Za-z0-9_-])/g, "\\\\$1"), input: a, selectedDay: 0, selectedMonth: 0, selectedYear: 0, drawMonth: 0, drawYear: 0, inline: b, dpDiv: !b ? this.dpDiv : d('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')} },
            _connectDatepicker: function(a, b) { var c = d(a); b.append = d([]); b.trigger = d([]); if (!c.hasClass(this.markerClassName)) { this._attachments(c, b); c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker", function(e, f, h) { b.settings[f] = h }).bind("getData.datepicker", function(e, f) { return this._get(b, f) }); this._autoSize(b); d.data(a, "datepicker", b) } }, _attachments: function(a, b) {
                var c = this._get(b, "appendText"), e = this._get(b, "isRTL"); b.append &&
b.append.remove(); if (c) { b.append = d('<span class="' + this._appendClass + '">' + c + "</span>"); a[e ? "before" : "after"](b.append) } a.unbind("focus", this._showDatepicker); b.trigger && b.trigger.remove(); c = this._get(b, "showOn"); if (c == "focus" || c == "both") a.focus(this._showDatepicker); if (c == "button" || c == "both") {
                    c = this._get(b, "buttonText"); var f = this._get(b, "buttonImage"); b.trigger = d(this._get(b, "buttonImageOnly") ? d("<img/>").addClass(this._triggerClass).attr({ src: f, alt: c, title: c }) : d('<button type="button"></button>').addClass(this._triggerClass).html(f ==
"" ? c : d("<img/>").attr({ src: f, alt: c, title: c }))); a[e ? "before" : "after"](b.trigger); b.trigger.click(function() { d.datepicker._datepickerShowing && d.datepicker._lastInput == a[0] ? d.datepicker._hideDatepicker() : d.datepicker._showDatepicker(a[0]); return false })
                } 
            }, _autoSize: function(a) {
                if (this._get(a, "autoSize") && !a.inline) {
                    var b = new Date(2009, 11, 20), c = this._get(a, "dateFormat"); if (c.match(/[DM]/)) {
                        var e = function(f) { for (var h = 0, i = 0, g = 0; g < f.length; g++) if (f[g].length > h) { h = f[g].length; i = g } return i }; b.setMonth(e(this._get(a,
c.match(/MM/) ? "monthNames" : "monthNamesShort"))); b.setDate(e(this._get(a, c.match(/DD/) ? "dayNames" : "dayNamesShort")) + 20 - b.getDay())
                    } a.input.attr("size", this._formatDate(a, b).length)
                } 
            }, _inlineDatepicker: function(a, b) {
                var c = d(a); if (!c.hasClass(this.markerClassName)) {
                    c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker", function(e, f, h) { b.settings[f] = h }).bind("getData.datepicker", function(e, f) { return this._get(b, f) }); d.data(a, "datepicker", b); this._setDate(b, this._getDefaultDate(b),
true); this._updateDatepicker(b); this._updateAlternate(b)
                } 
            }, _dialogDatepicker: function(a, b, c, e, f) {
                a = this._dialogInst; if (!a) { this.uuid += 1; this._dialogInput = d('<input type="text" id="' + ("dp" + this.uuid) + '" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'); this._dialogInput.keydown(this._doKeyDown); d("body").append(this._dialogInput); a = this._dialogInst = this._newInst(this._dialogInput, false); a.settings = {}; d.data(this._dialogInput[0], "datepicker", a) } E(a.settings, e || {}); b = b && b.constructor ==
Date ? this._formatDate(a, b) : b; this._dialogInput.val(b); this._pos = f ? f.length ? f : [f.pageX, f.pageY] : null; if (!this._pos) this._pos = [document.documentElement.clientWidth / 2 - 100 + (document.documentElement.scrollLeft || document.body.scrollLeft), document.documentElement.clientHeight / 2 - 150 + (document.documentElement.scrollTop || document.body.scrollTop)]; this._dialogInput.css("left", this._pos[0] + 20 + "px").css("top", this._pos[1] + "px"); a.settings.onSelect = c; this._inDialog = true; this.dpDiv.addClass(this._dialogClass); this._showDatepicker(this._dialogInput[0]);
                d.blockUI && d.blockUI(this.dpDiv); d.data(this._dialogInput[0], "datepicker", a); return this
            }, _destroyDatepicker: function(a) { var b = d(a), c = d.data(a, "datepicker"); if (b.hasClass(this.markerClassName)) { var e = a.nodeName.toLowerCase(); d.removeData(a, "datepicker"); if (e == "input") { c.append.remove(); c.trigger.remove(); b.removeClass(this.markerClassName).unbind("focus", this._showDatepicker).unbind("keydown", this._doKeyDown).unbind("keypress", this._doKeyPress).unbind("keyup", this._doKeyUp) } else if (e == "div" || e == "span") b.removeClass(this.markerClassName).empty() } },
            _enableDatepicker: function(a) { var b = d(a), c = d.data(a, "datepicker"); if (b.hasClass(this.markerClassName)) { var e = a.nodeName.toLowerCase(); if (e == "input") { a.disabled = false; c.trigger.filter("button").each(function() { this.disabled = false }).end().filter("img").css({ opacity: "1.0", cursor: "" }) } else if (e == "div" || e == "span") b.children("." + this._inlineClass).children().removeClass("ui-state-disabled"); this._disabledInputs = d.map(this._disabledInputs, function(f) { return f == a ? null : f }) } }, _disableDatepicker: function(a) {
                var b =
d(a), c = d.data(a, "datepicker"); if (b.hasClass(this.markerClassName)) { var e = a.nodeName.toLowerCase(); if (e == "input") { a.disabled = true; c.trigger.filter("button").each(function() { this.disabled = true }).end().filter("img").css({ opacity: "0.5", cursor: "default" }) } else if (e == "div" || e == "span") b.children("." + this._inlineClass).children().addClass("ui-state-disabled"); this._disabledInputs = d.map(this._disabledInputs, function(f) { return f == a ? null : f }); this._disabledInputs[this._disabledInputs.length] = a } 
            }, _isDisabledDatepicker: function(a) {
                if (!a) return false;
                for (var b = 0; b < this._disabledInputs.length; b++) if (this._disabledInputs[b] == a) return true; return false
            }, _getInst: function(a) { try { return d.data(a, "datepicker") } catch (b) { throw "Missing instance data for this datepicker"; } }, _optionDatepicker: function(a, b, c) {
                var e = this._getInst(a); if (arguments.length == 2 && typeof b == "string") return b == "defaults" ? d.extend({}, d.datepicker._defaults) : e ? b == "all" ? d.extend({}, e.settings) : this._get(e, b) : null; var f = b || {}; if (typeof b == "string") { f = {}; f[b] = c } if (e) {
                    this._curInst == e &&
this._hideDatepicker(); var h = this._getDateDatepicker(a, true); E(e.settings, f); this._attachments(d(a), e); this._autoSize(e); this._setDateDatepicker(a, h); this._updateDatepicker(e)
                } 
            }, _changeDatepicker: function(a, b, c) { this._optionDatepicker(a, b, c) }, _refreshDatepicker: function(a) { (a = this._getInst(a)) && this._updateDatepicker(a) }, _setDateDatepicker: function(a, b) { if (a = this._getInst(a)) { this._setDate(a, b); this._updateDatepicker(a); this._updateAlternate(a) } }, _getDateDatepicker: function(a, b) {
                (a = this._getInst(a)) &&
!a.inline && this._setDateFromField(a, b); return a ? this._getDate(a) : null
            }, _doKeyDown: function(a) {
                var b = d.datepicker._getInst(a.target), c = true, e = b.dpDiv.is(".ui-datepicker-rtl"); b._keyEvent = true; if (d.datepicker._datepickerShowing) switch (a.keyCode) {
                    case 9: d.datepicker._hideDatepicker(); c = false; break; case 13: c = d("td." + d.datepicker._dayOverClass, b.dpDiv).add(d("td." + d.datepicker._currentClass, b.dpDiv)); c[0] ? d.datepicker._selectDay(a.target, b.selectedMonth, b.selectedYear, c[0]) : d.datepicker._hideDatepicker();
                        return false; case 27: d.datepicker._hideDatepicker(); break; case 33: d.datepicker._adjustDate(a.target, a.ctrlKey ? -d.datepicker._get(b, "stepBigMonths") : -d.datepicker._get(b, "stepMonths"), "M"); break; case 34: d.datepicker._adjustDate(a.target, a.ctrlKey ? +d.datepicker._get(b, "stepBigMonths") : +d.datepicker._get(b, "stepMonths"), "M"); break; case 35: if (a.ctrlKey || a.metaKey) d.datepicker._clearDate(a.target); c = a.ctrlKey || a.metaKey; break; case 36: if (a.ctrlKey || a.metaKey) d.datepicker._gotoToday(a.target); c = a.ctrlKey ||
a.metaKey; break; case 37: if (a.ctrlKey || a.metaKey) d.datepicker._adjustDate(a.target, e ? +1 : -1, "D"); c = a.ctrlKey || a.metaKey; if (a.originalEvent.altKey) d.datepicker._adjustDate(a.target, a.ctrlKey ? -d.datepicker._get(b, "stepBigMonths") : -d.datepicker._get(b, "stepMonths"), "M"); break; case 38: if (a.ctrlKey || a.metaKey) d.datepicker._adjustDate(a.target, -7, "D"); c = a.ctrlKey || a.metaKey; break; case 39: if (a.ctrlKey || a.metaKey) d.datepicker._adjustDate(a.target, e ? -1 : +1, "D"); c = a.ctrlKey || a.metaKey; if (a.originalEvent.altKey) d.datepicker._adjustDate(a.target,
a.ctrlKey ? +d.datepicker._get(b, "stepBigMonths") : +d.datepicker._get(b, "stepMonths"), "M"); break; case 40: if (a.ctrlKey || a.metaKey) d.datepicker._adjustDate(a.target, +7, "D"); c = a.ctrlKey || a.metaKey; break; default: c = false
                } else if (a.keyCode == 36 && a.ctrlKey) d.datepicker._showDatepicker(this); else c = false; if (c) { a.preventDefault(); a.stopPropagation() } 
            }, _doKeyPress: function(a) {
                var b = d.datepicker._getInst(a.target); if (d.datepicker._get(b, "constrainInput")) {
                    b = d.datepicker._possibleChars(d.datepicker._get(b, "dateFormat"));
                    var c = String.fromCharCode(a.charCode == G ? a.keyCode : a.charCode); return a.ctrlKey || c < " " || !b || b.indexOf(c) > -1
                } 
            }, _doKeyUp: function(a) { a = d.datepicker._getInst(a.target); if (a.input.val() != a.lastVal) try { if (d.datepicker.parseDate(d.datepicker._get(a, "dateFormat"), a.input ? a.input.val() : null, d.datepicker._getFormatConfig(a))) { d.datepicker._setDateFromField(a); d.datepicker._updateAlternate(a); d.datepicker._updateDatepicker(a) } } catch (b) { d.datepicker.log(b) } return true }, _showDatepicker: function(a) {
                a = a.target ||
a; if (a.nodeName.toLowerCase() != "input") a = d("input", a.parentNode)[0]; if (!(d.datepicker._isDisabledDatepicker(a) || d.datepicker._lastInput == a)) {
                    var b = d.datepicker._getInst(a); d.datepicker._curInst && d.datepicker._curInst != b && d.datepicker._curInst.dpDiv.stop(true, true); var c = d.datepicker._get(b, "beforeShow"); E(b.settings, c ? c.apply(a, [a, b]) : {}); b.lastVal = null; d.datepicker._lastInput = a; d.datepicker._setDateFromField(b); if (d.datepicker._inDialog) a.value = ""; if (!d.datepicker._pos) {
                        d.datepicker._pos = d.datepicker._findPos(a);
                        d.datepicker._pos[1] += a.offsetHeight
                    } var e = false; d(a).parents().each(function() { e |= d(this).css("position") == "fixed"; return !e }); if (e && d.browser.opera) { d.datepicker._pos[0] -= document.documentElement.scrollLeft; d.datepicker._pos[1] -= document.documentElement.scrollTop } c = { left: d.datepicker._pos[0], top: d.datepicker._pos[1] }; d.datepicker._pos = null; b.dpDiv.css({ position: "absolute", display: "block", top: "-1000px" }); d.datepicker._updateDatepicker(b); c = d.datepicker._checkOffset(b, c, e); b.dpDiv.css({ position: d.datepicker._inDialog &&
d.blockUI ? "static" : e ? "fixed" : "absolute", display: "none", left: c.left + "px", top: c.top /*top*/ + "px"
                    }); if (!b.inline) {
                        c = d.datepicker._get(b, "showAnim"); var f = d.datepicker._get(b, "duration"), h = function() { d.datepicker._datepickerShowing = true; var i = d.datepicker._getBorders(b.dpDiv); b.dpDiv.find("iframe.ui-datepicker-cover").css({ left: -i[0], top: -i[1], width: b.dpDiv.outerWidth(), height: b.dpDiv.outerHeight() }) }; b.dpDiv.zIndex(d(a).zIndex() + 1); d.effects && d.effects[c] ? b.dpDiv.show(c, d.datepicker._get(b, "showOptions"), f,
h) : b.dpDiv[c || "show"](c ? f : null, h); if (!c || !f) h(); b.input.is(":visible") && !b.input.is(":disabled") && b.input.focus(); d.datepicker._curInst = b
                    } 
                } 
            }, _updateDatepicker: function(a) {
                var b = this, c = d.datepicker._getBorders(a.dpDiv); a.dpDiv.empty().append(this._generateHTML(a)).find("iframe.ui-datepicker-cover").css({ left: -c[0], top: -c[1], width: a.dpDiv.outerWidth(), height: a.dpDiv.outerHeight() }).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout", function() {
                    d(this).removeClass("ui-state-hover");
                    this.className.indexOf("ui-datepicker-prev") != -1 && d(this).removeClass("ui-datepicker-prev-hover"); this.className.indexOf("ui-datepicker-next") != -1 && d(this).removeClass("ui-datepicker-next-hover")
                }).bind("mouseover", function() {
                    if (!b._isDisabledDatepicker(a.inline ? a.dpDiv.parent()[0] : a.input[0])) {
                        d(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"); d(this).addClass("ui-state-hover"); this.className.indexOf("ui-datepicker-prev") != -1 && d(this).addClass("ui-datepicker-prev-hover");
                        this.className.indexOf("ui-datepicker-next") != -1 && d(this).addClass("ui-datepicker-next-hover")
                    } 
                }).end().find("." + this._dayOverClass + " a").trigger("mouseover").end(); c = this._getNumberOfMonths(a); var e = c[1]; e > 1 ? a.dpDiv.addClass("ui-datepicker-multi-" + e).css("width", 17 * e + "em") : a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""); a.dpDiv[(c[0] != 1 || c[1] != 1 ? "add" : "remove") + "Class"]("ui-datepicker-multi"); a.dpDiv[(this._get(a, "isRTL") ? "add" : "remove") + "Class"]("ui-datepicker-rtl");
                a == d.datepicker._curInst && d.datepicker._datepickerShowing && a.input && a.input.is(":visible") && !a.input.is(":disabled") && a.input.focus()
            }, _getBorders: function(a) { var b = function(c) { return { thin: 1, medium: 2, thick: 3}[c] || c }; return [parseFloat(b(a.css("border-left-width"))), parseFloat(b(a.css("border-top-width")))] }, _checkOffset: function(a, b, c) {
                var e = a.dpDiv.outerWidth(), f = a.dpDiv.outerHeight(), h = a.input ? a.input.outerWidth() : 0, i = a.input ? a.input.outerHeight() : 0, g = document.documentElement.clientWidth + d(document).scrollLeft(),
k = document.documentElement.clientHeight + d(document).scrollTop(); b.left -= this._get(a, "isRTL") ? e - h : 0; b.left -= c && b.left == a.input.offset().left ? d(document).scrollLeft() : 0; b.top -= c && b.top == a.input.offset().top + i ? d(document).scrollTop() : 0; b.left -= Math.min(b.left, b.left + e > g && g > e ? Math.abs(b.left + e - g) : 0); b.top -= Math.min(b.top, b.top + f > k && k > f ? Math.abs(f + i) : 0); return b
            }, _findPos: function(a) {
                for (var b = this._get(this._getInst(a), "isRTL"); a && (a.type == "hidden" || a.nodeType != 1); ) a = a[b ? "previousSibling" : "nextSibling"];
                a = d(a).offset(); return [a.left, a.top]
            }, _hideDatepicker: function(a) {
                var b = this._curInst; if (!(!b || a && b != d.data(a, "datepicker"))) if (this._datepickerShowing) {
                    a = this._get(b, "showAnim"); var c = this._get(b, "duration"), e = function() { d.datepicker._tidyDialog(b); this._curInst = null }; d.effects && d.effects[a] ? b.dpDiv.hide(a, d.datepicker._get(b, "showOptions"), c, e) : b.dpDiv[a == "slideDown" ? "slideUp" : a == "fadeIn" ? "fadeOut" : "hide"](a ? c : null, e); a || e(); if (a = this._get(b, "onClose")) a.apply(b.input ? b.input[0] : null, [b.input ? b.input.val() :
"", b]); this._datepickerShowing = false; this._lastInput = null; if (this._inDialog) { this._dialogInput.css({ position: "absolute", left: "0", top: "-100px" }); if (d.blockUI) { d.unblockUI(); d("body").append(this.dpDiv) } } this._inDialog = false
                } 
            }, _tidyDialog: function(a) { a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar") }, _checkExternalClick: function(a) {
                if (d.datepicker._curInst) {
                    a = d(a.target); a[0].id != d.datepicker._mainDivId && a.parents("#" + d.datepicker._mainDivId).length == 0 && !a.hasClass(d.datepicker.markerClassName) &&
!a.hasClass(d.datepicker._triggerClass) && d.datepicker._datepickerShowing && !(d.datepicker._inDialog && d.blockUI) && d.datepicker._hideDatepicker()
                } 
            }, _adjustDate: function(a, b, c) { a = d(a); var e = this._getInst(a[0]); if (!this._isDisabledDatepicker(a[0])) { this._adjustInstDate(e, b + (c == "M" ? this._get(e, "showCurrentAtPos") : 0), c); this._updateDatepicker(e) } }, _gotoToday: function(a) {
                a = d(a); var b = this._getInst(a[0]); if (this._get(b, "gotoCurrent") && b.currentDay) {
                    b.selectedDay = b.currentDay; b.drawMonth = b.selectedMonth = b.currentMonth;
                    b.drawYear = b.selectedYear = b.currentYear
                } else { var c = new Date; b.selectedDay = c.getDate(); b.drawMonth = b.selectedMonth = c.getMonth(); b.drawYear = b.selectedYear = c.getFullYear() } this._notifyChange(b); this._adjustDate(a)
            }, _selectMonthYear: function(a, b, c) { a = d(a); var e = this._getInst(a[0]); e._selectingMonthYear = false; e["selected" + (c == "M" ? "Month" : "Year")] = e["draw" + (c == "M" ? "Month" : "Year")] = parseInt(b.options[b.selectedIndex].value, 10); this._notifyChange(e); this._adjustDate(a) }, _clickMonthYear: function(a) {
                var b =
this._getInst(d(a)[0]); b.input && b._selectingMonthYear && setTimeout(function() { b.input.focus() }, 0); b._selectingMonthYear = !b._selectingMonthYear
            }, _selectDay: function(a, b, c, e) { var f = d(a); if (!(d(e).hasClass(this._unselectableClass) || this._isDisabledDatepicker(f[0]))) { f = this._getInst(f[0]); f.selectedDay = f.currentDay = d("a", e).html(); f.selectedMonth = f.currentMonth = b; f.selectedYear = f.currentYear = c; this._selectDate(a, this._formatDate(f, f.currentDay, f.currentMonth, f.currentYear)) } }, _clearDate: function(a) {
                a =
d(a); this._getInst(a[0]); this._selectDate(a, "")
            }, _selectDate: function(a, b) { a = this._getInst(d(a)[0]); b = b != null ? b : this._formatDate(a); a.input && a.input.val(b); this._updateAlternate(a); var c = this._get(a, "onSelect"); if (c) c.apply(a.input ? a.input[0] : null, [b, a]); else a.input && a.input.trigger("change"); if (a.inline) this._updateDatepicker(a); else { this._hideDatepicker(); this._lastInput = a.input[0]; typeof a.input[0] != "object" && a.input.focus(); this._lastInput = null } }, _updateAlternate: function(a) {
                var b = this._get(a,
"altField"); if (b) { var c = this._get(a, "altFormat") || this._get(a, "dateFormat"), e = this._getDate(a), f = this.formatDate(c, e, this._getFormatConfig(a)); d(b).each(function() { d(this).val(f) }) } 
            }, noWeekends: function(a) { a = a.getDay(); return [a > 0 && a < 6, ""] }, iso8601Week: function(a) { a = new Date(a.getTime()); a.setDate(a.getDate() + 4 - (a.getDay() || 7)); var b = a.getTime(); a.setMonth(0); a.setDate(1); return Math.floor(Math.round((b - a) / 864E5) / 7) + 1 }, parseDate: function(a, b, c) {
                if (a == null || b == null) throw "Invalid arguments"; b = typeof b ==
"object" ? b.toString() : b + ""; if (b == "") return null; for (var e = (c ? c.shortYearCutoff : null) || this._defaults.shortYearCutoff, f = (c ? c.dayNamesShort : null) || this._defaults.dayNamesShort, h = (c ? c.dayNames : null) || this._defaults.dayNames, i = (c ? c.monthNamesShort : null) || this._defaults.monthNamesShort, g = (c ? c.monthNames : null) || this._defaults.monthNames, k = c = -1, l = -1, u = -1, j = false, o = function(p) { (p = z + 1 < a.length && a.charAt(z + 1) == p) && z++; return p }, m = function(p) {
    o(p); p = new RegExp("^\\d{1," + (p == "@" ? 14 : p == "!" ? 20 : p == "y" ? 4 : p == "o" ?
3 : 2) + "}"); p = b.substring(s).match(p); if (!p) throw "Missing number at position " + s; s += p[0].length; return parseInt(p[0], 10)
}, n = function(p, w, H) { p = o(p) ? H : w; for (w = 0; w < p.length; w++) if (b.substr(s, p[w].length).toLowerCase() == p[w].toLowerCase()) { s += p[w].length; return w + 1 } throw "Unknown name at position " + s; }, r = function() { if (b.charAt(s) != a.charAt(z)) throw "Unexpected literal at position " + s; s++ }, s = 0, z = 0; z < a.length; z++) if (j) if (a.charAt(z) == "'" && !o("'")) j = false; else r(); else switch (a.charAt(z)) {
                    case "d": l = m("d");
                        break; case "D": n("D", f, h); break; case "o": u = m("o"); break; case "m": k = m("m"); break; case "M": k = n("M", i, g); break; case "y": c = m("y"); break; case "@": var v = new Date(m("@")); c = v.getFullYear(); k = v.getMonth() + 1; l = v.getDate(); break; case "!": v = new Date((m("!") - this._ticksTo1970) / 1E4); c = v.getFullYear(); k = v.getMonth() + 1; l = v.getDate(); break; case "'": if (o("'")) r(); else j = true; break; default: r()
                } if (c == -1) c = (new Date).getFullYear(); else if (c < 100) c += (new Date).getFullYear() - (new Date).getFullYear() % 100 + (c <= e ? 0 : -100); if (u >
-1) { k = 1; l = u; do { e = this._getDaysInMonth(c, k - 1); if (l <= e) break; k++; l -= e } while (1) } v = this._daylightSavingAdjust(new Date(c, k - 1, l)); if (v.getFullYear() != c || v.getMonth() + 1 != k || v.getDate() != l) throw "Invalid date"; return v
            }, ATOM: "yy-mm-dd", COOKIE: "D, dd M yy", ISO_8601: "yy-mm-dd", RFC_822: "D, d M y", RFC_850: "DD, dd-M-y", RFC_1036: "D, d M y", RFC_1123: "D, d M yy", RFC_2822: "D, d M yy", RSS: "D, d M y", TICKS: "!", TIMESTAMP: "@", W3C: "yy-mm-dd", _ticksTo1970: (718685 + Math.floor(492.5) - Math.floor(19.7) + Math.floor(4.925)) * 24 *
60 * 60 * 1E7, formatDate: function(a, b, c) {
    if (!b) return ""; var e = (c ? c.dayNamesShort : null) || this._defaults.dayNamesShort, f = (c ? c.dayNames : null) || this._defaults.dayNames, h = (c ? c.monthNamesShort : null) || this._defaults.monthNamesShort; c = (c ? c.monthNames : null) || this._defaults.monthNames; var i = function(o) { (o = j + 1 < a.length && a.charAt(j + 1) == o) && j++; return o }, g = function(o, m, n) { m = "" + m; if (i(o)) for (; m.length < n; ) m = "0" + m; return m }, k = function(o, m, n, r) { return i(o) ? r[m] : n[m] }, l = "", u = false; if (b) for (var j = 0; j < a.length; j++) if (u) if (a.charAt(j) ==
"'" && !i("'")) u = false; else l += a.charAt(j); else switch (a.charAt(j)) {
        case "d": l += g("d", b.getDate(), 2); break; case "D": l += k("D", b.getDay(), e, f); break; case "o": l += g("o", (b.getTime() - (new Date(b.getFullYear(), 0, 0)).getTime()) / 864E5, 3); break; case "m": l += g("m", b.getMonth() + 1, 2); break; case "M": l += k("M", b.getMonth(), h, c); break; case "y": l += i("y") ? b.getFullYear() : (b.getYear() % 100 < 10 ? "0" : "") + b.getYear() % 100; break; case "@": l += b.getTime(); break; case "!": l += b.getTime() * 1E4 + this._ticksTo1970; break; case "'": if (i("'")) l +=
"'"; else u = true; break; default: l += a.charAt(j)
    } return l
}, _possibleChars: function(a) { for (var b = "", c = false, e = function(h) { (h = f + 1 < a.length && a.charAt(f + 1) == h) && f++; return h }, f = 0; f < a.length; f++) if (c) if (a.charAt(f) == "'" && !e("'")) c = false; else b += a.charAt(f); else switch (a.charAt(f)) { case "d": case "m": case "y": case "@": b += "0123456789"; break; case "D": case "M": return null; case "'": if (e("'")) b += "'"; else c = true; break; default: b += a.charAt(f) } return b }, _get: function(a, b) { return a.settings[b] !== G ? a.settings[b] : this._defaults[b] },
            _setDateFromField: function(a, b) { if (a.input.val() != a.lastVal) { var c = this._get(a, "dateFormat"), e = a.lastVal = a.input ? a.input.val() : null, f, h; f = h = this._getDefaultDate(a); var i = this._getFormatConfig(a); try { f = this.parseDate(c, e, i) || h } catch (g) { this.log(g); e = b ? "" : e } a.selectedDay = f.getDate(); a.drawMonth = a.selectedMonth = f.getMonth(); a.drawYear = a.selectedYear = f.getFullYear(); a.currentDay = e ? f.getDate() : 0; a.currentMonth = e ? f.getMonth() : 0; a.currentYear = e ? f.getFullYear() : 0; this._adjustInstDate(a) } }, _getDefaultDate: function(a) {
                return this._restrictMinMax(a,
this._determineDate(a, this._get(a, "defaultDate"), new Date))
            }, _determineDate: function(a, b, c) {
                var e = function(h) { var i = new Date; i.setDate(i.getDate() + h); return i }, f = function(h) {
                    try { return d.datepicker.parseDate(d.datepicker._get(a, "dateFormat"), h, d.datepicker._getFormatConfig(a)) } catch (i) { } var g = (h.toLowerCase().match(/^c/) ? d.datepicker._getDate(a) : null) || new Date, k = g.getFullYear(), l = g.getMonth(); g = g.getDate(); for (var u = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g, j = u.exec(h); j; ) {
                        switch (j[2] || "d") {
                            case "d": case "D": g +=
parseInt(j[1], 10); break; case "w": case "W": g += parseInt(j[1], 10) * 7; break; case "m": case "M": l += parseInt(j[1], 10); g = Math.min(g, d.datepicker._getDaysInMonth(k, l)); break; case "y": case "Y": k += parseInt(j[1], 10); g = Math.min(g, d.datepicker._getDaysInMonth(k, l)); break
                        } j = u.exec(h)
                    } return new Date(k, l, g)
                }; if (b = (b = b == null ? c : typeof b == "string" ? f(b) : typeof b == "number" ? isNaN(b) ? c : e(b) : b) && b.toString() == "Invalid Date" ? c : b) { b.setHours(0); b.setMinutes(0); b.setSeconds(0); b.setMilliseconds(0) } return this._daylightSavingAdjust(b)
            },
            _daylightSavingAdjust: function(a) { if (!a) return null; a.setHours(a.getHours() > 12 ? a.getHours() + 2 : 0); return a }, _setDate: function(a, b, c) {
                var e = !b, f = a.selectedMonth, h = a.selectedYear; b = this._restrictMinMax(a, this._determineDate(a, b, new Date)); a.selectedDay = a.currentDay = b.getDate(); a.drawMonth = a.selectedMonth = a.currentMonth = b.getMonth(); a.drawYear = a.selectedYear = a.currentYear = b.getFullYear(); if ((f != a.selectedMonth || h != a.selectedYear) && !c) this._notifyChange(a); this._adjustInstDate(a); if (a.input) a.input.val(e ?
"" : this._formatDate(a))
            }, _getDate: function(a) { return !a.currentYear || a.input && a.input.val() == "" ? null : this._daylightSavingAdjust(new Date(a.currentYear, a.currentMonth, a.currentDay)) }, _generateHTML: function(a) {
                var b = new Date; b = this._daylightSavingAdjust(new Date(b.getFullYear(), b.getMonth(), b.getDate())); var c = this._get(a, "isRTL"), e = this._get(a, "showButtonPanel"), f = this._get(a, "hideIfNoPrevNext"), h = this._get(a, "navigationAsDateFormat"), i = this._getNumberOfMonths(a), g = this._get(a, "showCurrentAtPos"), k =
this._get(a, "stepMonths"), l = i[0] != 1 || i[1] != 1, u = this._daylightSavingAdjust(!a.currentDay ? new Date(9999, 9, 9) : new Date(a.currentYear, a.currentMonth, a.currentDay)), j = this._getMinMaxDate(a, "min"), o = this._getMinMaxDate(a, "max"); g = a.drawMonth - g; var m = a.drawYear; if (g < 0) { g += 12; m-- } if (o) { var n = this._daylightSavingAdjust(new Date(o.getFullYear(), o.getMonth() - i[0] * i[1] + 1, o.getDate())); for (n = j && n < j ? j : n; this._daylightSavingAdjust(new Date(m, g, 1)) > n; ) { g--; if (g < 0) { g = 11; m-- } } } a.drawMonth = g; a.drawYear = m; n = this._get(a,
"prevText"); n = !h ? n : this.formatDate(n, this._daylightSavingAdjust(new Date(m, g - k, 1)), this._getFormatConfig(a)); n = this._canAdjustMonth(a, -1, m, g) ? '<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + y + ".datepicker._adjustDate('#" + a.id + "', -" + k + ", 'M');\" title=\"" + n + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "e" : "w") + '">' + n + "</span></a>" : f ? "" : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="' + n + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "e" : "w") + '">' +
n + "</span></a>"; var r = this._get(a, "nextText"); r = !h ? r : this.formatDate(r, this._daylightSavingAdjust(new Date(m, g + k, 1)), this._getFormatConfig(a)); f = this._canAdjustMonth(a, +1, m, g) ? '<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + y + ".datepicker._adjustDate('#" + a.id + "', +" + k + ", 'M');\" title=\"" + r + '"><span class="ui-icon ui-icon-circle-triangle-' + (c ? "w" : "e") + '">' + r + "</span></a>" : f ? "" : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="' + r + '"><span class="ui-icon ui-icon-circle-triangle-' +
(c ? "w" : "e") + '">' + r + "</span></a>"; k = this._get(a, "currentText"); r = this._get(a, "gotoCurrent") && a.currentDay ? u : b; k = !h ? k : this.formatDate(k, r, this._getFormatConfig(a)); h = !a.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + y + '.datepicker._hideDatepicker();">' + this._get(a, "closeText") + "</button>" : ""; e = e ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (c ? h : "") + (this._isInRange(a, r) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' +
y + ".datepicker._gotoToday('#" + a.id + "');\">" + k + "</button>" : "") + (c ? "" : h) + "</div>" : ""; h = parseInt(this._get(a, "firstDay"), 10); h = isNaN(h) ? 0 : h; k = this._get(a, "showWeek"); r = this._get(a, "dayNames"); this._get(a, "dayNamesShort"); var s = this._get(a, "dayNamesMin"), z = this._get(a, "monthNames"), v = this._get(a, "monthNamesShort"), p = this._get(a, "beforeShowDay"), w = this._get(a, "showOtherMonths"), H = this._get(a, "selectOtherMonths"); this._get(a, "calculateWeek"); for (var L = this._getDefaultDate(a), I = "", C = 0; C < i[0]; C++) {
                    for (var M =
"", D = 0; D < i[1]; D++) {
                        var N = this._daylightSavingAdjust(new Date(m, g, a.selectedDay)), t = " ui-corner-all", x = ""; if (l) { x += '<div class="ui-datepicker-group'; if (i[1] > 1) switch (D) { case 0: x += " ui-datepicker-group-first"; t = " ui-corner-" + (c ? "right" : "left"); break; case i[1] - 1: x += " ui-datepicker-group-last"; t = " ui-corner-" + (c ? "left" : "right"); break; default: x += " ui-datepicker-group-middle"; t = ""; break } x += '">' } x += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + t + '">' + (/all|left/.test(t) && C == 0 ? c ?
f : n : "") + (/all|right/.test(t) && C == 0 ? c ? n : f : "") + this._generateMonthYearHeader(a, g, m, j, o, C > 0 || D > 0, z, v) + '</div><table class="ui-datepicker-calendar"><thead><tr>'; var A = k ? '<th class="ui-datepicker-week-col">' + this._get(a, "weekHeader") + "</th>" : ""; for (t = 0; t < 7; t++) { var q = (t + h) % 7; A += "<th" + ((t + h + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : "") + '><span title="' + r[q] + '">' + s[q] + "</span></th>" } x += A + "</tr></thead><tbody>"; A = this._getDaysInMonth(m, g); if (m == a.selectedYear && g == a.selectedMonth) a.selectedDay = Math.min(a.selectedDay,
A); t = (this._getFirstDayOfMonth(m, g) - h + 7) % 7; A = l ? 6 : Math.ceil((t + A) / 7); q = this._daylightSavingAdjust(new Date(m, g, 1 - t)); for (var O = 0; O < A; O++) {
                            x += "<tr>"; var P = !k ? "" : '<td class="ui-datepicker-week-col">' + this._get(a, "calculateWeek")(q) + "</td>"; for (t = 0; t < 7; t++) {
                                var F = p ? p.apply(a.input ? a.input[0] : null, [q]) : [true, ""], B = q.getMonth() != g, J = B && !H || !F[0] || j && q < j || o && q > o; P += '<td class="' + ((t + h + 6) % 7 >= 5 ? " ui-datepicker-week-end" : "") + (B ? " ui-datepicker-other-month" : "") + (q.getTime() == N.getTime() && g == a.selectedMonth &&
a._keyEvent || L.getTime() == q.getTime() && L.getTime() == N.getTime() ? " " + this._dayOverClass : "") + (J ? " " + this._unselectableClass + " ui-state-disabled" : "") + (B && !w ? "" : " " + F[1] + (q.getTime() == u.getTime() ? " " + this._currentClass : "") + (q.getTime() == b.getTime() ? " ui-datepicker-today" : "")) + '"' + ((!B || w) && F[2] ? ' title="' + F[2] + '"' : "") + (J ? "" : ' onclick="DP_jQuery_' + y + ".datepicker._selectDay('#" + a.id + "'," + q.getMonth() + "," + q.getFullYear() + ', this);return false;"') + ">" + (B && !w ? "&#xa0;" : J ? '<span class="ui-state-default">' + q.getDate() +
"</span>" : '<a class="ui-state-default' + (q.getTime() == b.getTime() ? " ui-state-highlight" : "") + (q.getTime() == u.getTime() ? " ui-state-active" : "") + (B ? " ui-priority-secondary" : "") + '" href="#">' + q.getDate() + "</a>") + "</td>"; q.setDate(q.getDate() + 1); q = this._daylightSavingAdjust(q)
                            } x += P + "</tr>"
                        } g++; if (g > 11) { g = 0; m++ } x += "</tbody></table>" + (l ? "</div>" + (i[0] > 0 && D == i[1] - 1 ? '<div class="ui-datepicker-row-break"></div>' : "") : ""); M += x
                    } I += M
                } I += e + (d.browser.msie && parseInt(d.browser.version, 10) < 7 && !a.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' :
""); a._keyEvent = false; return I
            }, _generateMonthYearHeader: function(a, b, c, e, f, h, i, g) {
                var k = this._get(a, "changeMonth"), l = this._get(a, "changeYear"), u = this._get(a, "showMonthAfterYear"), j = '<div class="ui-datepicker-title">', o = ""; if (h || !k) o += '<span class="ui-datepicker-month">' + i[b] + "</span>"; else {
                    i = e && e.getFullYear() == c; var m = f && f.getFullYear() == c; o += '<select class="ui-datepicker-month" onchange="DP_jQuery_' + y + ".datepicker._selectMonthYear('#" + a.id + "', this, 'M');\" onclick=\"DP_jQuery_" + y + ".datepicker._clickMonthYear('#" +
a.id + "');\">"; for (var n = 0; n < 12; n++) if ((!i || n >= e.getMonth()) && (!m || n <= f.getMonth())) o += '<option value="' + n + '"' + (n == b ? ' selected="selected"' : "") + ">" + g[n] + "</option>"; o += "</select>"
                } u || (j += o + (h || !(k && l) ? "&#xa0;" : "")); if (h || !l) j += '<span class="ui-datepicker-year">' + c + "</span>"; else {
                    g = this._get(a, "yearRange").split(":"); var r = (new Date).getFullYear(); i = function(s) { s = s.match(/c[+-].*/) ? c + parseInt(s.substring(1), 10) : s.match(/[+-].*/) ? r + parseInt(s, 10) : parseInt(s, 10); return isNaN(s) ? r : s }; b = i(g[0]); g = Math.max(b,
i(g[1] || "")); b = e ? Math.max(b, e.getFullYear()) : b; g = f ? Math.min(g, f.getFullYear()) : g; for (j += '<select class="ui-datepicker-year" onchange="DP_jQuery_' + y + ".datepicker._selectMonthYear('#" + a.id + "', this, 'Y');\" onclick=\"DP_jQuery_" + y + ".datepicker._clickMonthYear('#" + a.id + "');\">"; b <= g; b++) j += '<option value="' + b + '"' + (b == c ? ' selected="selected"' : "") + ">" + b + "</option>"; j += "</select>"
                } j += this._get(a, "yearSuffix"); if (u) j += (h || !(k && l) ? "&#xa0;" : "") + o; j += "</div>"; return j
            }, _adjustInstDate: function(a, b, c) {
                var e =
a.drawYear + (c == "Y" ? b : 0), f = a.drawMonth + (c == "M" ? b : 0); b = Math.min(a.selectedDay, this._getDaysInMonth(e, f)) + (c == "D" ? b : 0); e = this._restrictMinMax(a, this._daylightSavingAdjust(new Date(e, f, b))); a.selectedDay = e.getDate(); a.drawMonth = a.selectedMonth = e.getMonth(); a.drawYear = a.selectedYear = e.getFullYear(); if (c == "M" || c == "Y") this._notifyChange(a)
            }, _restrictMinMax: function(a, b) { var c = this._getMinMaxDate(a, "min"); a = this._getMinMaxDate(a, "max"); b = c && b < c ? c : b; return b = a && b > a ? a : b }, _notifyChange: function(a) {
                var b = this._get(a,
"onChangeMonthYear"); if (b) b.apply(a.input ? a.input[0] : null, [a.selectedYear, a.selectedMonth + 1, a])
            }, _getNumberOfMonths: function(a) { a = this._get(a, "numberOfMonths"); return a == null ? [1, 1] : typeof a == "number" ? [1, a] : a }, _getMinMaxDate: function(a, b) { return this._determineDate(a, this._get(a, b + "Date"), null) }, _getDaysInMonth: function(a, b) { return 32 - (new Date(a, b, 32)).getDate() }, _getFirstDayOfMonth: function(a, b) { return (new Date(a, b, 1)).getDay() }, _canAdjustMonth: function(a, b, c, e) {
                var f = this._getNumberOfMonths(a);
                c = this._daylightSavingAdjust(new Date(c, e + (b < 0 ? b : f[0] * f[1]), 1)); b < 0 && c.setDate(this._getDaysInMonth(c.getFullYear(), c.getMonth())); return this._isInRange(a, c)
            }, _isInRange: function(a, b) { var c = this._getMinMaxDate(a, "min"); a = this._getMinMaxDate(a, "max"); return (!c || b.getTime() >= c.getTime()) && (!a || b.getTime() <= a.getTime()) }, _getFormatConfig: function(a) {
                var b = this._get(a, "shortYearCutoff"); b = typeof b != "string" ? b : (new Date).getFullYear() % 100 + parseInt(b, 10); return { shortYearCutoff: b, dayNamesShort: this._get(a,
"dayNamesShort"), dayNames: this._get(a, "dayNames"), monthNamesShort: this._get(a, "monthNamesShort"), monthNames: this._get(a, "monthNames")}
                }, _formatDate: function(a, b, c, e) { if (!b) { a.currentDay = a.selectedDay; a.currentMonth = a.selectedMonth; a.currentYear = a.selectedYear } b = b ? typeof b == "object" ? b : this._daylightSavingAdjust(new Date(e, c, b)) : this._daylightSavingAdjust(new Date(a.currentYear, a.currentMonth, a.currentDay)); return this.formatDate(this._get(a, "dateFormat"), b, this._getFormatConfig(a)) } 
            }); d.fn.datepicker =
function(a) {
    if (!d.datepicker.initialized) { d(document).mousedown(d.datepicker._checkExternalClick).find("body").append(d.datepicker.dpDiv); d.datepicker.initialized = true } var b = Array.prototype.slice.call(arguments, 1); if (typeof a == "string" && (a == "isDisabled" || a == "getDate" || a == "widget")) return d.datepicker["_" + a + "Datepicker"].apply(d.datepicker, [this[0]].concat(b)); if (a == "option" && arguments.length == 2 && typeof arguments[1] == "string") return d.datepicker["_" + a + "Datepicker"].apply(d.datepicker, [this[0]].concat(b));
    return this.each(function() { typeof a == "string" ? d.datepicker["_" + a + "Datepicker"].apply(d.datepicker, [this].concat(b)) : d.datepicker._attachDatepicker(this, a) })
}; d.datepicker = new K; d.datepicker.initialized = false; d.datepicker.uuid = (new Date).getTime(); d.datepicker.version = "1.8.6"; window["DP_jQuery_" + y] = d
        })(jQuery);
        ;
        jQuery(function($) { $.datepicker.regional['es'] = { closeText: 'Cerrar', prevText: '&#x3c;Ant', nextText: 'Sig&#x3e;', currentText: 'Hoy', monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'], monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'], dayNames: ['Domingo', 'Lunes', 'Martes', 'Mi&eacute;rcoles', 'Jueves', 'Viernes', 'S&aacute;bado'], dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mi&eacute;', 'Juv', 'Vie', 'S&aacute;b'], dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'S&aacute;'], dateFormat: 'dd/mm/yy', firstDay: 0, isRTL: false }; });



(function($) {
    $.fn.custCheckBox = function(options) {

        var defaults = {
            disable_all: false, 			//disables all the elements
            hover: false, 					//adds a hover state to the tag
            wrapperclass: "group", 		//the class name of the wrapper tag
            callback: function() { } 		//a click event call back
        };
        //override defaults
        var opts = $.extend(defaults, options);

        return this.each(function() {
            var obj = $(this);

            $.fn.buildbox = function(thisElm) {

                $(thisElm).css({ display: "none" }).before("<span class=\"cust_checkbox\">&nbsp;&nbsp;&nbsp;&nbsp;</span>");
				
                var isChecked = $(thisElm).attr("checked");
                var boxtype = $(thisElm).attr("type");
                var disabled = $(thisElm).attr("disabled");

                if (boxtype === "checkbox") {
                    $(thisElm).prev("span").addClass("checkbox");
                    if (disabled || opts.disable_all) { boxtype = "checkbox_disabled"; }
                }
                else {
                    $(thisElm).prev("span").addClass("radio");
                    if (disabled || opts.disable_all) { boxtype = "radio_disabled"; }
                }

                if (isChecked)
                    $(thisElm).prev("span").addClass("cust_" + boxtype + "_on");
                else
                    $(thisElm).prev("span").addClass("cust_" + boxtype + "_off");

                if (opts.disable_all)
                    $(thisElm).attr("disabled", "disabled");


                //attach a click event for each label.
                $(thisElm).prev("span").prev("label").unbind().click(function() {

                    if (!opts.disable_all) {
                        var custbox = $(this).next("span");
                        var boxtype = $(custbox).next("input").attr("type");
                        var disabled = $(custbox).next("input").attr("disabled");

                        if ($(custbox).hasClass("checkbox")) {
                            if ($(custbox).hasClass("cust_" + boxtype + "_off") && !disabled) {
                                $(custbox).removeClass("cust_" + boxtype + "_off").addClass("cust_" + boxtype + "_on").next("input").attr("checked", "checked"); //turn on
                            }

                            else if (!disabled) {
                                $(custbox).removeClass("cust_" + boxtype + "_on").addClass("cust_" + boxtype + "_off").next("input").removeAttr("checked"); //turn off
                                $(custbox).removeClass("cust_" + boxtype + "_hvr");
                            }


                        }
                        else if (!disabled) {
                            $(custbox).parent().find(".cust_checkbox").removeClass("cust_" + boxtype + "_on").addClass("cust_" + boxtype + "_off").next("input").removeAttr("checked");
                            $(custbox).removeClass("cust_" + boxtype + "_off").addClass("cust_" + boxtype + "_on").next("input").attr("checked", "checked"); //turn on
                            $(custbox).removeClass("cust_" + boxtype + "_hvr");
                        }

                        opts.callback.call(this);

                    }

                }).hover(function() {
                    var custbox = $(this).next("span");
                    if ($(custbox).hasClass("cust_checkbox_on") && opts.hover)
                        $(custbox).addClass("cust_checkbox_hvr");
                    else if ($(custbox).hasClass("cust_radio_on") && opts.hover)
                        $(custbox).addClass("cust_radio_hvr");

                }, function() {
                    var custbox = $(this).next("span");
                    if ($(custbox).hasClass("cust_checkbox_on") && opts.hover)
                        $(custbox).removeClass("cust_checkbox_hvr");
                    else if ($(custbox).hasClass("cust_radio_on") && opts.hover)
                        $(custbox).removeClass("cust_radio_hvr");

                });

                //attach a click event for each checkbox.
                $(thisElm).prev("span").unbind().click(function() {
                    if (!opts.disable_all) {
                        var boxtype = $(this).next("input").attr("type");
                        var disabled = $(this).next("input").attr("disabled");
						
                        if ($(this).hasClass("checkbox")) {
                            if ($(this).hasClass("cust_" + boxtype + "_off") && !disabled)
                                $(this).removeClass("cust_" + boxtype + "_off").addClass("cust_" + boxtype + "_on").next("input").attr("checked", "checked"); //turn on
                            else if (!disabled) {
                                $(this).removeClass("cust_" + boxtype + "_on").addClass("cust_" + boxtype + "_off").next("input").removeAttr("checked"); //turn off
                                $(this).removeClass("cust_" + boxtype + "_hvr");
                            }
                        }
                        else if (!disabled) {
                            $(this).parent().find(".cust_checkbox").removeClass("cust_" + boxtype + "_on").addClass("cust_" + boxtype + "_off").next("input").removeAttr("checked");
                            $(this).removeClass("cust_" + boxtype + "_off").addClass("cust_" + boxtype + "_on").next("input").attr("checked", "checked"); //turn on
                        }

                        opts.callback.call(this);

                    }
                }).hover(function() {
                    if ($(this).hasClass("cust_checkbox_on") && opts.hover)
                        $(this).addClass("cust_checkbox_hvr");
                    else if ($(this).hasClass("cust_radio_on") && opts.hover)
                        $(this).addClass("cust_radio_hvr");
                }, function() {
                    if ($(this).hasClass("cust_checkbox_on") && opts.hover)
                        $(this).removeClass("cust_checkbox_hvr");
                    else if ($(this).hasClass("cust_radio_on") && opts.hover)
                        $(this).removeClass("cust_radio_hvr");
                });

            };

            //build the boxes
            $.fn.buildbox($(obj));




        });
    };

})(jQuery);

//toJSON
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);
    /**
 * jQuery custom selectboxes
 * 
 * Copyright (c) 2008 Krzysztof Suszyński (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 0.6.1
**/
jQuery.fn.selectbox = function(options){
	/* Default settings */
	var settings = {
		className: 'jquery-selectbox',
		animationSpeed: "fast",
		listboxMaxSize: 10,
		replaceInvisible: false
	};
	var commonClass = 'jquery-custom-selectboxes-replaced';
	var listOpen = false;
	var showList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideDown(settings.animationSpeed, function(){
			listOpen = true;
		});
		selectbox.addClass('selecthover');
		jQuery(document).bind('click', onBlurList);
		return listObj;
	}
	var hideList = function(listObj) {
		var selectbox = listObj.parents('.' + settings.className + '');
		listObj.slideUp(settings.animationSpeed, function(){
			listOpen = false;
			jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
		});
		jQuery(document).unbind('click', onBlurList);
		return listObj;
	}
	var onBlurList = function(e) {
		var trgt = e.target;
		var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
		if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
			hideList( jQuery('.' + commonClass + '-list') );
		}
		return false;
	}
	
	/* Processing settings */
	settings = jQuery.extend(settings, options || {});
	/* Wrapping all passed elements */
	return this.each(function() {
		var _this = jQuery(this);
		if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
			return;
		var replacement = jQuery(
			'<div class="' + settings.className + ' ' + commonClass + '">' +
				'<div class="' + settings.className + '-moreButton" >' +
                    '<div  class="' + settings.className + '-moreButton-img"/>' +
                '</div>' +
				'<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
				'<span class="' + settings.className + '-currentItem" />' +
			'</div>'
		);
		jQuery('option', _this).each(function(k,v){
			var v = jQuery(v);
			var listElement =  jQuery('<span class="' + settings.className + '-item value-'+v.val()+' item-'+k+'">' + v.text() + '</span>');	
			listElement.click(function(){
				var thisListElement = jQuery(this);
				var thisReplacment = thisListElement.parents('.'+settings.className);
				var thisIndex = thisListElement[0].className.split(' ');
				for( k1 in thisIndex ) {
					if(/^item-[0-9]+$/.test(thisIndex[k1])) {
						thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
						break;
					}
				};
				var thisValue = thisListElement[0].className.split(' ');
				for( k1 in thisValue ) {
					if(/^value-.+$/.test(thisValue[k1])) {
						thisValue = thisValue[k1].replace('value-','');
						break;
					}
				};
				thisReplacment
					.find('.' + settings.className + '-currentItem')
					.text(thisListElement.text());
				thisReplacment
					.find('select')
					.val(thisValue)
					.triggerHandler('change');
				var thisSublist = thisReplacment.find('.' + settings.className + '-list');
				if(thisSublist.filter(":visible").length > 0) {
					hideList( thisSublist );
				}else{
					showList( thisSublist );
				}
			}).bind('mouseenter',function(){
				jQuery(this).addClass('listelementhover');
			}).bind('mouseleave',function(){
				jQuery(this).removeClass('listelementhover');
			});
			jQuery('.' + settings.className + '-list', replacement).append(listElement);
			if(v.filter(':selected').length > 0) {
				jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
			}
		});
		replacement.find('.' + settings.className + '-moreButton').click(function(){
			var thisMoreButton = jQuery(this);
			var otherLists = jQuery('.' + settings.className + '-list')
				.not(thisMoreButton.siblings('.' + settings.className + '-list'));
			hideList( otherLists );
			var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
			if(thisList.filter(":visible").length > 0) {
				hideList( thisList );
			}else{
				showList( thisList );
			}
		}).bind('mouseenter',function(){
			jQuery(this).find('.' + settings.className + '-moreButton-img').addClass('morebuttonhover');
		}).bind('mouseleave',function(){
		    jQuery(this).find('.' + settings.className + '-moreButton-img').removeClass('morebuttonhover');
		});
		_this.hide().replaceWith(replacement).appendTo(replacement);
		var thisListBox = replacement.find('.' + settings.className + '-list');
		var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
		if(thisListBoxSize > settings.listboxMaxSize)
			thisListBoxSize = settings.listboxMaxSize;
		if(thisListBoxSize == 0)
			thisListBoxSize = 1;	
		var thisListBoxWidth = Math.round(_this.width() + 5);
		if(jQuery.browser.safari)
			thisListBoxWidth = thisListBoxWidth * 0.94;
		replacement.css('width', thisListBoxWidth + 'px');
		thisListBox.css({
			width: Math.round(thisListBoxWidth-5) + 'px'//,
			/*height: thisListBoxSize + 'em'*/
		});
	});
}
jQuery.fn.unselectbox = function(){
	var commonClass = 'jquery-custom-selectboxes-replaced';
	return this.each(function() {
		var selectToRemove = jQuery(this).filter('.' + commonClass);
		selectToRemove.replaceWith(selectToRemove.find('select').show());		
	});
}

