
var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
var monthNamesAbbr = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct", "Nov", "Dec"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var dayNamesAbbr = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

try{var $j = jQuery.noConflict();}catch(e){}

var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);

var infiniteScrollSensitivity = 20;
if(is_iphone)infiniteScrollSensitivity = 110;

var loadingAsMobile = false;

try {
	loadingAsMobile = (getCookie("LoadingAsMobile")=="true");
} catch (e) {
}

var sitePath = "";

try {
	sitePath = (getCookie("_SitePath"));
} catch (e) {
}

$j(document).ready(function() {

    if(!are_cookies_enabled()) alert("Please Enable Cookies for this site to function properly");

    setCookie("screenWidth",$j(window).width(),1);
    setCookie("screenHeight",$j(window).height(),1);
 
    var Sploders = $j("body").find(".mobileSploder");

    for (i=0;i<Sploders.length;i++)
    {
        var MoveDiv = $j(Sploders[i]).detach();
        $j("#defaultnetform").prepend(MoveDiv);
        $j("#BillPayForm").prepend(MoveDiv);
    }
    var mCombos = $j("body").find(".mobileComboSlide");

    for (i=0;i<mCombos.length;i++)
    {
        var MoveDiv = $j(mCombos[i]).detach();
        $j("#defaultnetform").prepend(MoveDiv);
    }
    var RadTextBoxes = $j("body").find(".RadInput");
    for (i=0;i<RadTextBoxes.length;i++)
    {
        var TB = $j(RadTextBoxes[i]);
//	TB.removeAttr("class");  
    }
    RadTextBoxes = $j("body").find(".rdfd_");
    for (i=0;i<RadTextBoxes.length;i++)
    {
        var TB = $j(RadTextBoxes[i]);
//	TB.css("margin", ""); 
    } 
    try
    {
       var isInIFrame = (window.location != window.parent.location) ? true : false;
       if(isInIFrame)
       {
           $j("#mobileBanner").addClass("sploder");
           $j("#mobileHeader").addClass("sploder");
           $j("#mobileFooter").addClass("sploder");
       }
    } catch(e) {}

    $j(".datepicker").datepicker(); 

    AdjustWindowSize(); 

    if ($j.ajaxPrefilter) {
        $j.ajaxPrefilter(function (options, originalOptions, jqXHR) { 
            options.url = options.url + ((options.url.indexOf("?") !== -1) ? "&" : "?") + "ts=" + new Date().getTime(); 
        });
    }
       
});

function useSessionStorage() { 
    try { 
	if (sessionStorage) {
		try { 
			sessionStorage.setItem("testKey", 1); 
			sessionStorage.removeItem("testKey"); 
			return true;
		} catch (error) {  
			if (error.code === DOMException.QUOTA_EXCEEDED_ERR && sessionStorage.length === 0) return false; 
		}
	} 
    } catch (e) {  
        return false;
    }
    return false;		
}

function isCheckboxChecked(cb) { 
	if (cb.attr("checked")=="checked") return true;
	if (cb.attr("checked")) return true;
	return false;
}

function FormatCurrency(tb) {
    var num = tb.value;
    tb.value = formatCurrency(num);
}
function formatCurrency(num, noCents) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        num.substring(num.length - (4 * i + 3));
    if (noCents) {
        return ((sign) ? '' : '-') + '$' + num;
    } else {
        return ((sign) ? '' : '-') + '$' + num + '.' + cents;
    }
}
function formatNumberCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
function UnformatCurrency(tb) {
    var num = tb.value;
    num = num.toString().replace(/\$|\,/g, '');
    tb.value = num;
}

function are_cookies_enabled()
{
	var cookieEnabled = (navigator.cookieEnabled) ? true : false;

	if (typeof navigator.cookieEnabled == "undefined" && !cookieEnabled)
	{ 
		document.cookie="testcookie";
		cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
	}
	return (cookieEnabled);
}

function dataFix(d) {
	try
	{
		return (d.d) ? d.d : d;
	} catch(e) {
		return d;
	}
}

function AdjustWindowSize()
{
    var wrappingHeight = 0;
    if($j("#mobileBanner").outerHeight(true))wrappingHeight = wrappingHeight + $j("#mobileBanner").outerHeight(true);
    if($j("#mobileHeader").outerHeight(true))wrappingHeight = wrappingHeight + $j("#mobileHeader").outerHeight(true);
    if($j("#mobileFooter").outerHeight(true))wrappingHeight = wrappingHeight + $j("#mobileFooter").outerHeight(true);
    wrappingHeight = wrappingHeight + $j("#content").outerHeight(true)-$j("#content").height();
    if(is_iphone) wrappingHeight = wrappingHeight - 60;
    $j("#content").css("min-height",($j(window).height()-wrappingHeight));
    window.setTimeout("window.scrollTo(0,0)",250);
} 

function hasFileUpload() {
    var el = document.createElement("input");
    el.setAttribute("type", "file");
    return !el.disabled;
}

function hasTouchSupport()
{
	var support = {},
            events = ['touchstart', 'touchmove', 'touchend'],
            el = document.createElement('div'), i;

        try {
          for(i=0; i<events.length; i++) {
            var eventName = events[i];
            eventName = 'on' + eventName;
            var isSupported = (eventName in el);
            if (!isSupported) {
              el.setAttribute(eventName, 'return;');
              isSupported = typeof el[eventName] == 'function';
            }
            support[events[i]] = isSupported;
          }
          return support.touchstart && support.touchend && support.touchmove;
        }
        catch(err) {
          return false;
        } 
}

function FormatDate(d)
{
    return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
}

Date.prototype.addDays = function(days) { 
this.setDate(this.getDate()+days); 
} 

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

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


function AttachCredentialValidation(UserID, Credential, TextboxID, ConfirmTextboxID, OutputDivID) {
    var Textbox;
    if (TextboxID !== "") Textbox = $j("#" + TextboxID)
    var ConfirmTextbox;
    if (ConfirmTextboxID !== "") ConfirmTextbox = $j("#" + ConfirmTextboxID);
    var OutputDiv;
    if (OutputDivID !== "") OutputDiv = $j("#" + OutputDivID)
    if (Textbox.length !== 1) return;
    var PathToASMX = sitePath + "/A_Master/NET/Login/Credentials.asmx"
    $j.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: PathToASMX + "/GetValidateLoginCredentialJSON",
        data: "{\"UserID\": \"" + UserID + "\",\"Credential\": \"" + Credential + "\"}",
        dataType: "json",
        success: function (data) { 
            var criteria = data.d;
            //alert(criteria);
            outputValidationCriteria(Textbox, ConfirmTextbox, OutputDiv, criteria); 
            Textbox.focus(function () { if ($j(this).val().trim() === "********") $j(this).val(""); outputValidationCriteria(Textbox, ConfirmTextbox, OutputDiv, criteria); });
            Textbox.blur(function () { if ($j(this).val().trim() === "" && $j(this).attr("isdefault") === "true") $j(this).val("********"); outputValidationCriteria(Textbox, ConfirmTextbox, OutputDiv, criteria); });
            Textbox.keyup(function () { outputValidationCriteria(Textbox, ConfirmTextbox, OutputDiv, criteria); });
            if (ConfirmTextbox && ConfirmTextbox.length === 1) {
                ConfirmTextbox.after($j("<span/>").addClass("credentialInputValidator").attr("id", ConfirmTextboxID + "_validator"));
                ConfirmTextbox.keyup(function () { checkValidationIsEqual(Textbox, ConfirmTextbox); });
            }
            Textbox.after($j("<span/>").addClass("credentialInputValidator").attr("id", TextboxID + "_validator"));
        },
        error: function (xhr, status, error) { alert(xhr.responseText); }
    });
}
function checkValidationIsEqual(Textbox, ConfirmTextbox) {
    var inputValidator = $j("#" + ConfirmTextbox.attr("id") + "_validator");
    inputValidator.removeClass("isValid");
    inputValidator.removeClass("notValid");
    if (Textbox.val() === "" || ConfirmTextbox.val() === "") return;
    if (Textbox.val() === ConfirmTextbox.val()) {
        inputValidator.addClass("isValid");
    } else {
        inputValidator.addClass("notValid");
    }
}
function outputValidationCriteria(Textbox, ConfirmTextbox, OutputDiv, Criteria) {
    var evaled = eval("(" + Criteria + ")");
    OutputDiv.html("");
    OutputDiv.removeClass("criteriaValidationWrapper");
    OutputDiv.addClass("criteriaValidationWrapper");
    OutputDiv.hide();
    var input = Textbox.val().trim();
    var ul = $j("<ul/>").appendTo(OutputDiv);
    var inputIsValid = true;
    $j.each(evaled, function (key, Criteria) {
        var isValid = false;
        if (input !== "") { //do the validation
            switch (Criteria.Type) {
                case "MinChars":
                    if (input.length >= Criteria.Value) isValid = true;
                    break;
                case "MaxChars":
                    if (input.length < Criteria.Value) isValid = true;
                    break;
                case "LCaseChars":
                    var LCaseCount = 0;
                    for (var i = 0; i < input.length; i++) {
                        if (input.charCodeAt(i) >= 97 && input.charCodeAt(i) <= 122) LCaseCount++;
                    }
                    if (LCaseCount >= Criteria.Value) isValid = true;
                    break;
                case "UCaseChars":
                    var UCaseCount = 0;
                    for (var i = 0; i < input.length; i++) {
                        if (input.charCodeAt(i) >= 65 && input.charCodeAt(i) <= 90) UCaseCount++;
                    }
                    if (UCaseCount >= Criteria.Value) isValid = true;
                    break;
                case "NumericChars":
                    var NumericCount = 0;
                    for (var i = 0; i < input.length; i++) {
                        if (input.charCodeAt(i) >= 48 && input.charCodeAt(i) <= 57) NumericCount++;
                    }
                    if (NumericCount >= Criteria.Value) isValid = true;
                    break;
                case "SpecialChars":
                    var SpecialCount = 0;
                    for (var i = 0; i < input.length; i++) {
                        if (input.charCodeAt(i) >= 33 && input.charCodeAt(i) <= 47) SpecialCount++;
                        if (input.charCodeAt(i) >= 58 && input.charCodeAt(i) <= 64) SpecialCount++;
                        if (input.charCodeAt(i) >= 91 && input.charCodeAt(i) <= 96) SpecialCount++;
                        if (input.charCodeAt(i) >= 123 && input.charCodeAt(i) <= 126) SpecialCount++;
                    }
                    if (SpecialCount >= Criteria.Value) isValid = true;
                    break;
                case "NoFirstName":
                    if (input.toLowerCase().indexOf(Criteria.Value) === -1) isValid = true;
                    break;
                case "NoLastName":
                    if (input.toLowerCase().indexOf(Criteria.Value) === -1) isValid = true;
                    break;
                case "NotOppositeReversed":
                    if (input.toLowerCase() !== Criteria.Value) isValid = true;
                    break;
                case "NotOpposite":
                    if (input.toLowerCase() !== Criteria.Value) isValid = true;
                    break;
                case "NoContainOpposite":
                    if (input.toLowerCase().indexOf(Criteria.Value) === -1) isValid = true;
                    break;
                case "AllowedPasswords":
                    isValid = true
                    break;
                default:
                    isValid = true;
            }
            if (!isValid) inputIsValid = false;
        }
        var li = $j("<li/>").appendTo(ul);
        if (Criteria.Type === "AllowedPasswords" || Criteria.Type === "NotInUseByAnotherAccount") {
        } else {
            li.addClass((isValid) ? "isValid" : "notValid");
        }
        var div = $j("<div/>").appendTo(li);
        $j("<span/>").addClass("validateImage").addClass().appendTo(div);
        $j("<span/>").addClass("validateText").html(Criteria.DisplayString).appendTo(div);
    });
    var inputValidator = $j("#" + Textbox.attr("id") + "_validator");
    inputValidator.removeClass("isValid");
    inputValidator.removeClass("notValid");
    if (input !== "") inputValidator.addClass((inputIsValid) ? "isValid" : "notValid");
    if (!inputIsValid || Textbox.is(":focus") || input === "") OutputDiv.show();
    if (ConfirmTextbox) checkValidationIsEqual(Textbox, ConfirmTextbox); 
    if (evaled.length === 0) {
        OutputDiv.hide();
        inputValidator.hide();
    }
    if (input === "********") {
        OutputDiv.hide();
        inputValidator.removeClass("isValid");
        inputValidator.removeClass("notValid");
    }
}






// Trim Strings -------------------------------------------------------------------------------------------------------
function Trim(sString,trimChar)
{
	return rTrim(lTrim(sString,trimChar),trimChar);
}
function lTrim(sString,trimChar)
{
	while (sString.substring(0,1) == trimChar)
	{
		sString = sString.substring(1, sString.length);
	}
	return sString;
}
function rTrim(sString,trimChar)
{
	while (sString.substring(sString.length-1, sString.length) == trimChar)
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;
}
// GENERIC OPENING -----------------------------------------------------------------------------------------------------------

function OpenNewWindow(url, name, options) {
	var temp = window.open(url, name, options);
	if (temp)	{
    		temp.focus();
	} else {
		alert('Please Enable popups for this site to continue');return false;
	}
	return temp;
	}
function OpenModule(WName, PageName, Width, Height, Parameters) {
	var temp = OpenModule2(WName,PageName,Width,Height,Parameters,0,0,0,1,0,1);
	}
function OpenModule2(WName, PageName, Width, Height, Parameters, Menubar, ToolBar, Location, ScrollBar, StatusBar, Resize) {
	// The URL for the facility detail
	var url = 'default.aspx?p=' + PageName + '&NoModResize=1&NoNav=1&ShowFooter=False&' + Parameters;
	var urlpath =document.location.href;
	urlpath= urlpath.substring(7,urlpath.length-7);
	var i
	if (urlpath.indexOf('ceclients') >= 0)
	{
		i = urlpath.indexOf('/d');
		if (i<0){
				i = urlpath.indexOf('/D');
			}
	
	}
	else
	{
		i = urlpath.indexOf('index.html');
	}

	urlpath = 'http://' + urlpath.substring(0,i+1);
	if (urlpath.length<=7)
	{
		urlpath =document.location.href + '';
	}
	
	url = urlpath+url;
	// Open the window
	var temp = OpenURL(url, WName, Width, Height, Menubar, ToolBar, Location, ScrollBar, StatusBar, Resize);
	}

function OpenURL(url, WName, Width, Height, Menubar, ToolBar, Location, ScrollBar, StatusBar, Resize) {

	// Get the window settings, set defaults if no settings are provided
	if(ToolBar == 1) {showToolBar = 'toolbar=yes';} else {showToolBar = 'toolbar=no';}
	if(Menubar == 1) {showMenuBar = 'menubar=yes';} else {showMenuBar = 'menubar=no';}
	if(Location == 1) {showLocation = 'location=yes';} else {showLocation = 'location=no';}
	if(ScrollBar == 1) {showScrollBar = 'scrollbars=yes';} else {showScrollBar = 'scrollbars=no';}
	if(StatusBar == 1) {showStatusBar = 'status=yes';} else {showStatusBar = 'status=no';}
	if(Resize == 1) {showResize = 'resizable=yes';} else {showResize = 'resizable=no';}

	// Get this window's position
	var x = 0;
	var y = 0;
	var w = 0;
	var h = 0;
	w = screen.AvailWidth;
	h = screen.AvailHeight;

	// Modify the position - CENTER THE NEW WINDOW
	x = (w-Width)/2;
	y = (h-Height)/2;

	// Open the window
	var temp = OpenNewWindow(url, WName, 'width=' + Width + ',height=' + Height + ',' + showStatusBar + ',' + showToolBar + ',' + showMenuBar + ',' + showLocation + ',' + showScrollBar + ',' + showResize + ',screenX=' + x + ',screenY=' + y + ',left=' + x + ',top=' + y);
	if (WName=='billing') {setTimeout('try{parent.navmenu.location.href = parent.navmenu.location.href;}catch(e){} window.location.href=window.location.href;',5000);}
	} 

// SPLODERS ------------------------------------------------------------------------------------------------------------------

 
var FocusedDiv;

function SploderLoaded(id)
{  
 	try { 
		hideLoader(id.replace("Div","") + "LoadingDiv");
	} catch(e) {}	
	var iFrame = document.getElementById(id + "iframe"); 
	if(iFrame)iFrame.style.display='block'; 
	var loadDiv = document.getElementById(id + "LoadingDiv");
	if(loadDiv)loadDiv.style.display='none';
	autoResizeIframe(id + "iframe"); 
	parent.setTimeout("window.scrollTo(0,0);",10);
	window.scrollTo(0,0);
	if(iFrame)iFrame.contentWindow.scrollTo(0,0);
}
function toggleDiv(id,height,width,centerme,grayOut,href) 
{   
	if ($j("#" + id).css("display") == "none") 
	{	
		enableDiv(id,height,width,centerme,grayOut);		 
	} else {
		disableDiv(id,height,width,centerme,grayOut);
	}
} 
function enableDiv(id,height,width,centerme,grayOut,href) 
{  
	
	enableDiv2(id,height,width,centerme,grayOut,href);
}
function enableDivNoResize(id,height,width,centerme,grayOut,href) 
{  
	enableDiv2(id,height,width,centerme,grayOut,href);
}
function enableDiv2(id,height,width,centerme,grayOut,href) 
{   
 	try {
		document.getElementById(id.replace("Div","") + "LoadingDiv").style.display='block';
        	document.getElementById(id.replace("Div","") + "iframe").style.display='none';
		showLoader(id.replace("Div","") + "LoadingDiv");
	} catch(e) {}	

        var Div = $j("#" + id);  
        $j(".mobileSploder").hide();
	//$j("#" + id).show('slide', {direction: 'right' }); 
	$j("#" + id).show(); 
	$j("#contentWrapper").hide();
	FocusedDiv = id; 
	if(id=="socialItemsLightboxDiv")
	{	
		var wrappingHeight = $j(window).height()-$j("#socialItemsLightboxDiv .sploderTitleBar").outerHeight();
		if(is_iphone) wrappingHeight = wrappingHeight + 60;
		$j("#socialItemsLightboxiframe").css("height",wrappingHeight); 
	}
	window.scrollTo(0,0);
}
function disableDiv(id,height,width,centerme,grayOut) 
{  
	$j(".mobileSploder").hide();
	$j("#contentWrapper").show(); //'slide', {direction: 'left' }, 325); 
	FocusedDiv = null;
	window.scrollTo(0,0);
} 
function resizeEnabledDiv(height,width)
{ 
	//do nothing, it's already full screen
}
function setEnabledDivTitle(title)
{
	if(!FocusedDiv)return;
	id = FocusedDiv; 
	id = Left(id,id.length-3) + "Span";	
	var titleObj = document.getElementById(id); 
	if(titleObj)titleObj.innerHTML = title;
}

function closeAllAxisDialogs() {
    $j(".axisDialogBox").trigger("closeDialog");
}
function closeDialog() {
    var axisDialogBoxes = $j(".axisDialogBox").length;
    if (axisDialogBoxes == 1) {
        $j(".axisDialogBox").trigger("closeDialog");
        return;
    } else if (axisDialogBoxes > 1) {
        
    }
    if (!FocusedDiv && parent) parent.setTimeout("closeDialog();", 100);
    if (!FocusedDiv) return;
    disableDiv(FocusedDiv);
}
function autoResizeIframe(id)
{
	
	var newheight;
	var newwidth;
	if(document.getElementById){
		newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
		newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
	} 
	document.getElementById(id).height = (newheight) + "px";
	document.getElementById(id).width = "100%"; //(newwidth) + "px";
} 

// Slide Comboboxes-----------------------------------------------------------------------------------------------------------

 
var FocusedCombo;
var FocusedComboOnUpdated=false;
var FocusedComboOnUpdate=null;
var FocusedComboEmptyMessage='';
var FocusedComboOffsetTop=0;
 function enableCombo(id,caller,emptyMessage,OnUpdate) 
{  
    var Div = $j("#" + id);
    FocusedComboOffsetTop=$j(caller).offset().top;
    $j("#contentWrapper").css('position','absolute');
    $j("#" + id).css('position','absolute');
	if ($j(caller).parents('.mobileCombo').parent().find('.mobileComboSlide').length>0){
		//updated slide
		$j("#" + id).html($j(caller).parents('.mobileCombo').parent().find('.mobileComboSlide').html());
	}
    $j(".mobileComboSlide").hide();
	$j("#contentWrapper").fadeOut('fast');
	$j("#" + id).show('slide', {direction: 'down' },function(){if(window.parent){window.parent.setTimeout('$j(window).scrollTop(0);',0);}else{$j(window).scrollTop(0);}$j("#contentWrapper").css('position','static');$j("#" + id).css('position','static');}); 
	FocusedCombo = id;
	FocusedComboOnUpdate=null; 
	FocusedComboOnUpdate = OnUpdate;
	FocusedComboOnUpdated=false;
	FocusedComboEmptyMessage=emptyMessage;
	if($j(caller).val()==emptyMessage){$j(caller).val('');$j(caller).removeClass('empty');}
}
function disableCombo(id) 
{  
    $j("#contentWrapper").css('position','absolute');
    $j("#" + id+"_Slide").css('position','absolute');
    $j("#" + id + "_Slide").fadeOut('fast');
	$j("#contentWrapper").show('slide', {direction: 'up' },function(){if(window.parent){window.parent.setTimeout('$j(window).scrollTop('+parseInt(FocusedComboOffsetTop)+');',0);}else{$j(window).scrollTop(parseInt(FocusedComboOffsetTop));};FocusedComboOffsetTop=0;$j("#contentWrapper").css('position','static');$j("#" + id+"_Slide").css('position','static');}); 
    FocusedCombo = null;
	if(FocusedComboOnUpdate&&FocusedComboOnUpdated){FocusedComboOnUpdate();}
	FocusedComboOnUpdate=null;
	FocusedComboOnUpdated=false;
	if($j('#'+id).find('input').val()==''){$j('#'+id).find('input').val(FocusedComboEmptyMessage);$j('#'+id).find('input').addClass('empty');}
}   
function doComboSelect(id,item,selId,multiselect)
{
	
	if(multiselect==false){$j('#'+id).find('input').val('');$j('#'+selId).val('');$j(item).parent().find('li').each(function(){$j(this).removeClass('selected');})}
	var txt=$j('#'+id).find('input').val();
	var val=$j('#'+selId).val();
	if ($j(item).attr('val')!='unselect')
	{
		if ($j(item).hasClass('selected'))
		{
			$j(item).removeClass('selected');
			txt=txt.replace(new RegExp($j(item).attr('txt')+', ','gi'),'');
			txt=txt.replace(new RegExp($j(item).attr('txt')+',','gi'),'');
			txt=txt.replace(new RegExp($j(item).attr('txt'),'gi'),'');
			val=val.replace(new RegExp($j(item).attr('val')+', ','gi'),'');
			val=val.replace(new RegExp($j(item).attr('val')+',','gi'),'');
			val=val.replace(new RegExp($j(item).attr('val'),'gi'),'');
		}
		else
		{
			$j(item).addClass('selected');
			txt += ', '+$j(item).attr('txt')+', ';
			val += ', '+$j(item).attr('val')+', ';
		}
	}
	else
	{
		$j('#'+id).find('input').val('');txt='';
		$j('#'+selId).val('');val='';
		$j(item).parent().find('li').each(function(){$j(this).removeClass('selected');})
		multiselect=false;
	}
	$j('#'+id).find('input').val(lTrim(lTrim(rTrim(rTrim(txt,' '),','),','),' '));
	$j('#'+selId).val(lTrim(lTrim(rTrim(rTrim(val,' '),','),','),' '));
	FocusedComboOnUpdated=true;
	if (multiselect==false){disableCombo(id);}
}

// Slide Dateboxes-----------------------------------------------------------------------------------------------------------

 
var FocusedDateBox;
var FocusedDateBoxOnUpdated=false;
var FocusedDateBoxOnUpdate=null;
var FocusedDateBoxEmptyMessage='';
var FocusedDateBoxOffsetTop = 0;
function enableDateBox(id,caller,OnUpdate) 
{  
    var Div = $j("#" + id);  
    FocusedDateBoxOffsetTop=$j(caller).offset().top;
    $j("#contentWrapper").css('position','absolute');
    $j("#" + id).css('position','absolute');
    $j(".mobileDateBoxSlide").fadeOut('fast');
	$j("#contentWrapper").hide('slide', {direction: 'down'} );
	$j("#" + id).show('slide', {direction: 'up' },function(){if(window.parent){window.parent.setTimeout('$j(window).scrollTo(0,0);',0);}else{$j(window).scrollTo(0,0);}$j("#contentWrapper").css('position','static');$j("#" + id).css('position','static');}); 
	FocusedDateBox = id;
	FocusedDateBoxOnUpdate=null; 
	FocusedDateBoxOnUpdate = OnUpdate;
	FocusedDateBoxOnUpdated=false;
}
function disableDateBox(id) 
{  
	$j("#contentWrapper").css('position','absolute');
    $j("#" + id+"_Slide").css('position','absolute');
    $j("#" + id + "_Slide").fadeOut('fast');
	$j("#contentWrapper").show('slide', {direction: 'up' },function(){if(window.parent){window.parent.setTimeout('$j(window).scrollTo('+parseInt(FocusedDateBoxOffsetTop)+');',0);}else{$j(window).scrollTo(0,parseInt(FocusedDateBoxOffsetTop));};FocusedDateBoxOffsetTop=0;$j("#contentWrapper").css('position','static');$j("#" + id+"_Slide").css('position','static');}); 
	FocusedDateBox = null;
	if(FocusedDateBoxOnUpdate&&FocusedDateBoxOnUpdated){FocusedDateBoxOnUpdate();}
	FocusedDateBoxOnUpdate=null;
	FocusedDateBoxOnUpdated=false;
	if($j('#'+id).find('input').val()==''){$j('#'+id).find('input').val(FocusedDateBoxEmptyMessage);$j('#'+id).find('input').addClass('empty');}
}   
function doDateBoxSelect(id,datetext,slide)
{
	var txt=$j('#'+id).find('input').val(datetext);
	FocusedDateBoxOnUpdated=true;
	if (slide==true){
	    disableDateBox(id);}
	else{
	    if(FocusedDateBoxOnUpdate&&FocusedDateBoxOnUpdated){
	        FocusedDateBoxOnUpdate();
	    }
	    FocusedDateBoxOnUpdate=null;
	    FocusedDateBoxOnUpdated=false;
	}
}
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,

		meta = {

			'\b': '\\b',

			'\t': '\\t',

			'\n': '\\n',

			'\f': '\\f',

			'\r': '\\r',

			'"' : '\\"',

			'\\': '\\\\'

		};

function JSONescape(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;
}
function Left(str, n)
{
        if(n <= 0)							// Invalid bound, return blank string
                return '';
        else if (n > String(str).length)	// Invalid bound, return
                return str;					// entire string
        else								// Valid bound, return appropriate substring
                return String(str).substring(0,n);
}

function Right(str, n)
{
        if (n <= 0)							// Invalid bound, return blank string
           return "";
        else if (n > String(str).length)	// Invalid bound, return
           return str;						// entire string
        else {								// Valid bound, return appropriate substring
           var iLen = String(str).length;
           return String(str).substring(iLen, iLen - n);
        }
}


// LOADIFY -------------------------------------------------------------------------------------------------------------------

function hideLoader(id)
{  
	var revertHtml = $j("#" + id).find("#spinnerCurrHtml_" + id).html();
	$j("#" + id).html(revertHtml);	
}
function showLoader(id,speed,src)
{  
	var cog = new Image();
	var rotation = 0;	
	cog.src = (src) ? src : "/A_Master/Mobile/css/images/loading_spinner.png"; 
	speed = (speed) ? speed : 10;
	var currHtml = $j("#" + id).html();
	currHtml = "<div id=\"spinnerCurrHtml_" + id + "\" style=\"display: none;\">" + currHtml + "</div>";
	$j("#" + id).html("<canvas id=\"spinner_" + id + "\" height=\"" + cog.height + "\" width=\"" + cog.width + "\"></canvas>" + currHtml);	
	setTimeout( function () { drawLoader(id,cog,rotation,speed); }, speed); 
} 
function drawLoader(id,cog,rotation,speed)
{ 
	var ctx = document.getElementById('spinner_' + id)
	if(!ctx) return;
	ctx = ctx.getContext('2d');
	ctx.globalCompositeOperation = 'destination-over';
	ctx.save();
	ctx.clearRect(0,0,cog.width,cog.height);
	ctx.translate(cog.width/2,cog.height/2);  
	rotation +=1;
	ctx.rotate(rotation*Math.PI/64);  
	ctx.translate(-cog.width/2,-cog.height/2);  
	ctx.drawImage(cog,0,0);
	ctx.restore(); 
	setTimeout( function () { drawLoader(id,cog,rotation,speed); }, speed); 
}

// JQUERY CUSTOM EVENTS ---------------------------------------------------------------------------------------------------------


//SWIPE

(function($) {

   $.fn.swipe=function(options) {

      var defaults=
      {
         threshold:{x:50,y:50},
         cancelThreshold:{x:50,y:50},
         touchHold:function(){},

 	 touchHoldThreshhold:1000,

         touchHolding:function(){},

 	 touchHoldingThreshhold:500,

         swipeLeft:function(){},

         swipeRight:function(){},

         swipeUp:function(){},

         swipeDown:function(){},

         swipingLeft:function(){},

         swipingRight:function(){},

         swipingUp:function(){},

         swipingDown:function(){}
      };

      var options=$.extend(defaults,options);
      if(!this)return false;

      return this.each( function() {


         var me=$(this)


         var originalCoord = {x:0,y:0};

         var finalCoord = {x:0,y:0};

         var cancelX = false;

         var cancelY = false;
	 var start = 0;
         var end = 0;
         var mouseDown = false; 
         var holdingTimer = null;


         function touchStart(event) 

         { 
            //if( navigator.userAgent.toLowerCase().indexOf("android")>=0 ) {event.preventDefault();}

	    if (hasTouchSupport()) {
                originalCoord.x=event.targetTouches[0].pageX;

                originalCoord.y=event.targetTouches[0].pageY;
            } else {
		originalCoord.x=event.screenX;
		originalCoord.y=event.screenY;
		mouseDown = true;
	    }
            cancelX=cancelY=false;

            finalCoord = {x:originalCoord.x,y:originalCoord.y}
	    var d = new Date();
            start = d.getTime(); 
	    holdingTimer = window.setTimeout(defaults.touchHolding,defaults.touchHoldingThreshhold);
         }


         function touchMove(event) 

         { 

 	    try { window.clearTimeout(holdingTimer); } catch(e) {}
            //if( navigator.userAgent.toLowerCase().indexOf("android")>=0 ) {event.preventDefault();}
      
	    if (hasTouchSupport()) {
                finalCoord.x=event.targetTouches[0].pageX;

                finalCoord.y=event.targetTouches[0].pageY;

            } else {
		if(!mouseDown)return;
		finalCoord.x=event.screenX;
		finalCoord.y=event.screenY;
	    }      
            var changeY=originalCoord.y-finalCoord.y;

            var changeX=originalCoord.x-finalCoord.x;


            if(cancelX)event.preventDefault();

            if(cancelY)event.preventDefault();	    

            if(defaults.swipingUp!="function () {}")event.preventDefault();

	    if(defaults.swipingDown!="function () {}")event.preventDefault();   
	    if(defaults.swipeUp!="function () {}")event.preventDefault();

	    if(defaults.swipeDown!="function () {}")event.preventDefault();



            //if(changeX > defaults.cancelThreshold.x || changeX < (defaults.cancelThreshold.x*-1)) cancelY = true;

            //if(changeY > defaults.cancelThreshold.y || changeY < (defaults.cancelThreshold.y*-1)) cancelX = true;

	

            if(!cancelX && changeX > defaults.threshold.x) 
            


            {
   
            defaults.swipingLeft();

               cancelX = true;

            }
	

            if(!cancelX && changeX < (defaults.threshold.x*-1)) 

            {

               defaults.swipingRight();

               cancelX = true;

            }


            if(!cancelY && changeY > defaults.threshold.y) 
            


            {
   
            defaults.swipingUp();

               cancelY = true;

            }
	

            if(!cancelY && changeY < (defaults.threshold.y*-1)) 

            {

               defaults.swipingDown();

               cancelY = true;

            }
           

         }


         function touchEnd(event)

         {   

 	    try { window.clearTimeout(holdingTimer); } catch(e) {}            
            if (navigator.userAgent.toLowerCase().indexOf("android")>=0)
            {
		if (finalCoord.x==0&&finalCoord.y==0){try{setTimeout('document.location.href="'+$j(this).find('a').attr('href')+'";',50);return;} catch(e){}}
                var ydiff = originalCoord.y-finalCoord.y
                //$j('html,body').animate({ scrollTop: $j('html,body').scrollTop()+ydiff }, { duration: 'fast', easing: 'swing'});
            }
            var changeY=originalCoord.y-finalCoord.y;

            var changeX=originalCoord.x-finalCoord.x;            
            if(changeY > defaults.threshold.y) { defaults.swipeUp(); }	

            else if(changeY < (defaults.threshold.y*-1)) { defaults.swipeDown(); }
            else if(changeX > defaults.threshold.x) { defaults.swipeLeft(); }  
	    else if(changeX < (defaults.threshold.x*-1)) { defaults.swipeRight(); }	

            else {
	 	var d = new Date();
            	end = d.getTime();

		if(end-start>=defaults.touchHoldThreshhold) defaults.touchHold();
	    }
	    mouseDown = false;	
	 }


         function touchCancel(event){
		cancelX=cancelY=false;
	 }

	if(hasTouchSupport())
	{
	 
	 this.addEventListener("touchstart",touchStart,false);

         this.addEventListener("touchmove",touchMove,false);

         this.addEventListener("touchend",touchEnd,false);

         this.addEventListener("touchcancel",touchCancel,false);
	} else { 

	 this.addEventListener("mousedown",touchStart,false);

	 this.addEventListener("mousemove",touchMove,false);

	 this.addEventListener("mouseup",touchEnd,false);
	}


      });  

   };  

})(jQuery);  

//END SWIPE