var iu;
var pe;
var refreshAction = null;
var updateAction = null;
var packmode = false;
var EmptyGuid = '00000000-0000-0000-0000-000000000000';
var resizeOffset = 0;
var isauthenticatedTimeout = 60000; // timeout check authenticated user
var isnewmasterpage = false;
var loadingdialog = null;
var postbackCode = null;
var isie6 = false;

// BeginRequestHandler and EndRequestHandler for showing the progress indicator for updatepanels
function BeginRequestHandler(sender, args) {
	ShowLoadingDialog();
}

function EndRequestHandler(sender, args) {
	var errorArgs = args.get_error();
	if (errorArgs != null) {
		DisplayAjaxErrorMessage(args.get_error().description);
		args.set_errorHandled(true);
	}
	else {
		HideLoadingDialog();
	}
}

// prototype a function for postValidation
window.postValidate = function() { }

//overwrite the confirm() and remember the old implementation in _confirm();
window._confirm = window.confirm;
window.confirm = function(questionmnemonic, titlemnemonic, okAction, cancelAction, specificDialog) {
	if (!okAction || !cancelAction) {
		return _confirm(questionmnemonic);
		//alert('WARNING: confirm() has been overwritten as a custom function.\n\nUse _confirm if you wish to use the original version\n\nconfirm() now takes 4 arguments, the question mnemonic, the title mnemonic, the okAction (javascript function) and the cancelAction.');
		//return;
	}
	window.confirmOkAction = function() { DisableButton('okButton'); okAction(); };
	window.confirmCancelAction = function() { DisableButton('cancelButton'); cancelAction(); };

	if (typeof (specificDialog) == 'undefined') { specificDialog = 'dialogMedium'; }

	eXpress.Web.UI.Website.UiService.GetGenericConfirmDialog(questionmnemonic, titlemnemonic, specificDialog, RenderSmallDialog);
}

function YesNoDialog(questionmnemonic, titlemnemonic, okAction, cancelAction, specificDialog) {
	window.confirmOkAction = function() { DisableButton('okButton'); okAction(); };
	window.confirmCancelAction = function() { DisableButton('cancelButton'); cancelAction(); };

	if (typeof (specificDialog) == 'undefined') { specificDialog = 'YesNoDialog'; }

	eXpress.Web.UI.Website.UiService.GetGenericConfirmDialog(questionmnemonic, titlemnemonic, specificDialog, RenderSmallDialog);
}

window.bconfirm = function(questionmnemonic, titlemnemonic, okAction, cancelAction, specificDialog) {
	if (!okAction || !cancelAction) {
		alert('WARNING: confirm() has been overwritten as a custom function.\n\nUse _confirm if you wish to use the original version\n\nconfirm() now takes 3 arguments, the question, the okAction (javascript function) and the cancelAction.');
		return;
	}
	window.confirmOkAction = function() { DisableButton('okButton'); okAction(); };
	window.confirmCancelAction = function() { DisableButton('cancelButton'); cancelAction(); };
	eXpress.Web.UI.Website.UiService.GetGenericConfirmDialog(questionmnemonic, titlemnemonic, specificDialog, RenderBigDialog);
}

// overwrite the alert() and remember the old implementation in _alert();
window._alert = window.alert;
window.alert = function(message) {
	eXpress.Web.UI.Website.UiService.GetGenericAlertDialog(message, RenderErrorDialog);
}

window.lalert = function(mnemonic) {
	if (arguments.length == 1) {
		eXpress.Web.UI.Website.UiService.GetGenericLocalizedAlertDialog(mnemonic, RenderErrorDialog);
	}
	else {
		eXpress.Web.UI.Website.UiService.GetGenericLocalizedAlertDialogWithArgs(mnemonic, RenderErrorDialog);
	}
}

function actionalert(message, action) {
	window.confirmOkAction = function() { PerformCloseDialog(); DisableButton('okButton'); action(); };
	eXpress.Web.UI.Website.UiService.GetGenericActionAlertDialog(message, RenderErrorDialog);
}

function actionconfirm(message, action) {
	window.confirmOkAction = function() { DisableButton('okButton'); action(); };
	eXpress.Web.UI.Website.UiService.GetGenericActionAlertDialog(message, RenderWarnDialog);
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

//---------------------------------------------------
// Ajax typeconvertors
//---------------------------------------------------

Guid = function() {
	this._typeName = 'Guid';
}

//---------------------------------------------------------------------
// general functions
//---------------------------------------------------------------------
function DisableButton(buttonIid) {
	if ($get(buttonIid))
		$get(buttonIid).disabled = true;
}

function ctrlPressed(evt) {
	var ctrlPressed = 0;
	if (parseInt(navigator.appVersion) > 3) {
		ctrlPressed = evt.ctrlKey;
	}
	return ctrlPressed;
}

function shiftPressed(evt) {
	var shiftPressed = 0;
	if (parseInt(navigator.appVersion) > 3) {
		shiftPressed = evt.shiftKey;
	}
	return shiftPressed;
}

function altPressed(evt) {
	var altPressed = 0;
	if (parseInt(navigator.appVersion) > 3) {
		altPressed = evt.altKey;
	}
	return altPressed;
}

function RedirectTo() {
	var url = "" + window.location;
	if (url.indexOf("editor.aspx") > -1) {
		window.location = "producterror.aspx";
	}
	else {
		//postback
		window.location.reload();
	}
}

function RedirectTo500() {
	window.location = "/500.aspx";
}

function PerformPostBack() {
	if (postbackCode) {
		window.setTimeout(postbackCode, 0);
	}
	WebForm_InitCallback();
}

function ToggleTreeNode(nid) {
	var theme = $get(nid);
	var childs = theme.parentNode.nextSibling;
	if (getStyle(childs, 'display') == 'block')
		childs.style.display = 'none';
	else
		childs.style.display = 'block';
	SwitchClass(nid, 'expandTheme', 'collapseTheme');
}

var session_Timer1 = null;
var session_Timer2 = null;
function checkSession() {
	clearTimeout(session_Timer1);
	clearTimeout(session_Timer2);
	session_Timer1 = window.setTimeout(checkSession_onTick, isauthenticatedTimeout);
}

function checkSession_onTick() {
	clearTimeout(session_Timer1);
	clearTimeout(session_Timer2);
	eXpress.Web.UI.Website.UiService.IsAuthenticated(checkSession_onTick_Complete);
}

function checkSession_onTick_Complete(AuthFunctionResult) {
	clearTimeout(session_Timer1);
	clearTimeout(session_Timer2);
	if (AuthFunctionResult.AuthResult > 1) {
		alert(AuthFunctionResult.Message);
	}
	else {
		session_Timer2 = window.setTimeout(checkSession, isauthenticatedTimeout);
	}
}

// not used
function MaintainSession() {
	_alert('Maintain');
	try {
		$.ajax({
			type: "POST",
			url: "/UiService.asmx/IsAuthenticated",
			data: "{}",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(msg) {
				clearTimeout(session_Timer1);

				_alert(msg);

				session_Timer1 = window.setTimeout(MaintainSession, isauthenticatedTimeout);
			},
			error: function(e) {
				clearTimeout(session_Timer1);
				_alert(e);
				session_Timer1 = window.setTimeout(MaintainSession, isauthenticatedTimeout);

			}
		});
	} catch (exc) { }
}

function NoEnter() {
	return !(window.event && window.event.keyCode == 13);
}

function CheckValue(textbox) {
	var v = "0123456789";
	var w = "";
	for (i = 0; i < textbox.value.length; i++) {
		x = textbox.value.charAt(i);
		if (v.indexOf(x, 0) != -1)
			w += x;
	}
	if (w == 0) { w = 1; }
	textbox.value = w;
}

function CurrencyFormatted(amount, divider) {
	var i = parseFloat(amount);
	if (isNaN(i)) { i = 0.00; }
	var minus = '';
	if (i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if (s.indexOf('.') < 0) { s += '.00'; }
	if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;

	var result = null;
	if (divider) {
		if (divider == ',') {
			result = s.replace('.', ',');
		}
		else {
			result = s.replace(',', '.');
		}
	}
	else {
		result = s.replace('.', ',');
	}

	return result;
}

function PopulateDropDownList(element, OptionText, OptionValue, data) {
	var el = $get(element);
	var ddl = (el.control == null ? new Sys.Preview.UI.Selector(el) : el.control)
	ddl.set_textProperty(OptionText);
	ddl.set_valueProperty(OptionValue);
	ddl.set_data(data);
	ddl.set_firstItemText(' ');
	ddl.set_selectedValue('');
	el.disabled = false;
	window['s_' + element] = ddl;
}

// Select the radio button when the table is clicked
function radioSelect(srcEl, evt, radiob, seg) {
	var r = $get(radiob);
	if (r.type != 'checkbox') {
		r.checked = true;
	}
	else {
		// See if we clicked on the checkbox, if so, don't do anything with it
		var originalTarget = null;
		if (isIE) originalTarget = evt.srcElement;
		else originalTarget = evt.originalTarget;
		if (originalTarget.type != "checkbox") {
			r.checked = !r.checked;
		}
	}
	var ctype = r.getAttribute("ctype");
	if (r.checked) {
		selectedContacts.push(r.value);
		if (ctype == "cg")
			window.ShareContactGroupIds.push(r.value);
		else
			window.ShareContactIds.push(r.value)
	}
	else {
		selectedContacts.pop(r.value);
		if (ctype == "cg")
			window.ShareContactGroupIds.pop(r.value);
		else
			window.ShareContactIds.pop(r.value)
	}
	segmentSelect(r, null, seg);
}

// Selects the group in the first dialog of sharing
function segmentSelect(b, table, segment) {
	var segment = $get(segment);
	var tables = segment.getElementsByTagName('table');
	for (var i = 0; i < tables.length; i++) {
		var tab = tables[i];
		var radioB = tab.getElementsByTagName('input');
		if (radioB && radioB[0]) {
			if (radioB[0].checked == true) {
				tab.style.border = "1px solid #00B5F1";
			}
			else {
				tab.style.border = "1px solid #FFFFFF";
				tab.style.borderLeft = "1px solid #FFFFFF";
			}
		}
	}
}

/*
Toggles visibility of one or more elements
*/
function Toggle() {
	// Note: only works on block display elements
	for (var i = 0; i < arguments.length; i++) {
		var ctl = $get(arguments[i]);

		if (ctl != null) {
			if (getStyle(ctl, 'display') == 'block')
				ctl.style.display = 'none';
			else
				ctl.style.display = 'block';
		}
	}
}

function getStyle(element, style) {
	var value = element.style[style];
	if (!value) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			var css = document.defaultView.getComputedStyle(element, null);
			value = css ? css.getPropertyValue(style) : null;
		} else if (element.currentStyle) {
			value = element.currentStyle[style];
		}
	}

	return value;
}

function LimitMultiLineLength(obj, e) {
	var re = new RegExp("\r\n", "g");
	x = obj.value.replace(re, "").length;

	if (x > obj.getAttribute("maxLength")) {
		if (obj.getAttribute("ErrorMessage")) {
			alert(obj.getAttribute("ErrorMessage"));
		}
		return false;
	}
	return true;
}

function FindFocusableElement(parent) {
	var firstLink = null;
	var children = parent.childNodes;
	for (var i = 0; i < children.length; i++) {
		if (children[i].tagName == 'INPUT' || children[i].tagName == 'TEXTAREA' || children[i].tagName == 'SELECT') {
			if (!children[i].disabled) {
				if (children[i].tagName != 'INPUT' || children[i].type != 'hidden')
					return children[i];
			}
		}
		else if (children[i].tagName == 'A') {
			if (!firstLink)
				firstLink = children[i];
		}
		else if (children[i].childNodes.length > 0) {
			var e = FindFocusableElement(children[i]);
			if (e && e.tagName != 'A')
				return e;
			else if (!firstLink)
				firstLink = e;
		}
	}
	return firstLink;
}

function ScrollDown(id) {
	$get(id).scrollTop = $get(id).scrollTop + 60;
}

function ZIndex() {
	var elements = document.getElementsByTagName('li');
	var counter = 1;
	for (var i = elements.length - 1; i > 0; i--) {
		elements[i].style.zIndex = counter;
		counter++;
	}
}

// used for help dialogs
function ShowHelp(mnemonic) {
	window.confirmOkAction = CloseDialog;
	eXpress.Web.UI.Website.UiService.GetGenericOkDialog(mnemonic, null, OnShowHelp);
}

function OnShowHelp(obj) {
	RenderBigDialog(obj);
}

function FailedCallback(error, userContext, methodName) {
	if (error !== null) {

		DisplayAjaxErrorMessage(error.get_message());
	}
	else {
		DisplayAjaxErrorMessage("Unknown error.");
	}
}

function DisplayAjaxErrorMessage(message) {
	RenderErrorDialog("<div class=\"dialogTop\"><div class=\"dialogLogo\"></div></div><div class=\"dialogMiddle\" style=\"text-align:center\">" + message + "</div><div class=\"boxButtons\" style=\"text-align:center\"><input type=\"button\" style=\"width:50px\" value=\"Ok\" onclick=\"RedirectTo500();\"></div><div class=\"dialogBottom\"></div>");
}

if (typeof (Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


/*
BEGIN Impulse buying Options
*/

// used for the options popup
function SetState(visualObject) {
	var fieldId = visualObject.id.replace("visual_", "");
	var field = $get(fieldId);
	if (field) {
		if (field.type == "radio") {
			field.checked = true;
		}
		else if (field.type == "checkbox") {
			field.checked = !field.checked;
		}
	}
	SetOptionDisplay();
}

// set the visual state
function SetOptionDisplay() {
	var css = "selected";
	jQuery("#dialogData input").each(function() {
		var obj = jQuery("#visual_" + this.id);
		jHover(obj, this.checked, css);

		if (!obj.hasClass("nothanks")) {
			var li = $get("visual_" + this.id);
			if (this.checked) {
				RCAddIn(li);
			}
			else {
				RCOut(li);
			}
		}
	});
}

function CallOptionsImpulsBuy(cartItemId, style) {
	if (style == "dialogSmall") {
		eXpress.Web.UI.Website.UiService.GetOptionsImpulsBuy(cartItemId, ShowCallOptionsImpulsBuySmallComplete);
	}
	else if (style == "dialogLarge") {
		eXpress.Web.UI.Website.UiService.GetOptionsImpulsBuy(cartItemId, ShowCallOptionsImpulsBuyLargeComplete);
	}
	else {
		eXpress.Web.UI.Website.UiService.GetOptionsImpulsBuy(cartItemId, ShowCallOptionsImpulsBuyGiantComplete);
	}
}

function ShowCallOptionsImpulsBuySmallComplete(result) {
	PerformShowCallOptionsImpulsBuyComplete(result, "dialogSmall");
}

function ShowCallOptionsImpulsBuyLargeComplete(result) {
	PerformShowCallOptionsImpulsBuyComplete(result, "dialogLarge");
}

function ShowCallOptionsImpulsBuyGiantComplete(result) {
	PerformShowCallOptionsImpulsBuyComplete(result, "dialogGiant");
}


function PerformShowCallOptionsImpulsBuyComplete(result, cssClass) {
	CreateOverlayDialog(result, true, cssClass);

	var selected = $get("ctl01_SelectedOptions");
	var ids = new Array();
	ids = selected.value.split(",");

	// activate the selection from the shopping basket
	for (var i = 0; i < ids.length; i++) {
		jQuery("div#dialogData input").each(function() {
			if (this.value.toLowerCase() == ids[i].toLowerCase()) {
				this.checked = true;
			}
		});
	}

	SetOptionDisplay();
}

function CancelOptionsImpulsBuy(url) {
	document.location.href = url;
	//CloseDialog();
}

function PerformOptionsImpulsBuy(urlShoppingBasket) {
	var cartItemId = $get("ctl01_CartItemId").value;
	var optionCodes = "";
	jQuery("div#dialogData input").each(function() {
		if (this.checked) {
			optionCodes += this.value + ",";
		}
	});
	eXpress.Web.UI.Website.UiService.PerformOptionsImulseBuy(cartItemId, optionCodes, PerformOptionsImpulsBuyComplete);
}

function PerformOptionsImpulsBuyComplete(result) {
	document.location.href = '/cart/';

}
/*
END Impulse buying Options
*/
// Set paging

var countTotalImages = 0;

function SetPagerData(prefix, fldid, listClientId, currentPage, totalPages, totalImages) {
	countTotalImages = totalImages;
	if (currentPage == 0) currentPage = 1;
	if (totalPages == 0) totalPages = 1;

	var pagerLnkFirst = $get(prefix + "_lnkFirst");
	var pagerLnkPrev = $get(prefix + "_lnkPrev");
	var pagerSpCurrent = $get(prefix + "_spCurrent");
	var pagerSpTotalPages = $get(prefix + "_spTotalPages");
	var pagerLnkNext = $get(prefix + "_lnkNext");
	var pagerLnkLast = $get(prefix + "_lnkLast");
	var pagerDivFirst = $get(prefix + "_divFirst");
	var pagerDivPrev = $get(prefix + "_divPrev");
	var pagerDivNext = $get(prefix + "_divNext");
	var pagerDivLast = $get(prefix + "_divLast");
	var totalimagecounter = $get(prefix + 'selectedImagesCounterTotal');

	if (pagerLnkFirst) {
		pagerLnkFirst.href = "javascript:ChangePage_" + prefix + "('" + fldid + "', 1, '" + listClientId + "');";
	}

	if (pagerLnkPrev) {
		pagerLnkPrev.href = "javascript:ChangePage_" + prefix + "('" + fldid + "', " + (parseInt(currentPage) - 1) + ", '" + listClientId + "');";
	}

	if (pagerSpCurrent) {
		if (currentPage <= 0) {
			// This happens when the albums are empty
			currentPage = 1;
		}
		pagerSpCurrent.innerHTML = " " + currentPage.toString() + " ";
	}

	if (pagerSpTotalPages) {
		pagerSpTotalPages.innerHTML = " " + totalPages.toString();
	}

	if (pagerLnkNext) {
		pagerLnkNext.href = "javascript:ChangePage_" + prefix + "('" + fldid + "', " + (parseInt(currentPage) + 1) + ", '" + listClientId + "');";
	}

	if (pagerLnkLast) {
		pagerLnkLast.href = "javascript:ChangePage_" + prefix + "('" + fldid + "', " + totalPages + ", '" + listClientId + "');";
	}

	if (totalimagecounter) {
		totalimagecounter.innerHTML = totalImages;
	}

	// Set/hide pager buttons 
	if (pagerDivFirst && pagerDivPrev && pagerDivNext && pagerDivLast) {
		if (totalPages == 1) {
			pagerLnkFirst.className = "btnFastBackward hide";
			pagerLnkPrev.className = "btnBackward hide";
			pagerDivFirst.className = "btnFastBackward";
			pagerDivPrev.className = "btnBackward";
			pagerLnkNext.className = "btnForward hide";
			pagerLnkLast.className = "btnFastForward hide";
			pagerDivNext.className = "btnForward";
			pagerDivLast.className = "btnFastForward";
		}
		else if (currentPage == 1) {
			pagerLnkFirst.className = "btnFastBackward hide";
			pagerLnkPrev.className = "btnBackward hide";
			pagerDivFirst.className = "btnFastBackward";
			pagerDivPrev.className = "btnBackward";
			pagerLnkNext.className = "btnForward";
			pagerLnkLast.className = "btnFastForward";
			pagerDivNext.className = "btnForward hide";
			pagerDivLast.className = "btnFastForward hide";

		}
		else if (currentPage == totalPages) {
			pagerLnkFirst.className = "btnFastBackward";
			pagerLnkPrev.className = "btnBackward";
			pagerDivFirst.className = "btnFastBackward hide";
			pagerDivPrev.className = "btnBackward hide";
			pagerLnkNext.className = "btnForward hide";
			pagerLnkLast.className = "btnFastForward hide";
			pagerDivNext.className = "btnForward";
			pagerDivLast.className = "btnFastForward";
		}
		else {
			pagerLnkFirst.className = "btnFastBackward";
			pagerLnkPrev.className = "btnBackward";
			pagerDivFirst.className = "btnFastBackward hide";
			pagerDivPrev.className = "btnBackward hide";
			pagerLnkNext.className = "btnForward";
			pagerLnkLast.className = "btnFastForward";
			pagerDivNext.className = "btnForward hide";
			pagerDivLast.className = "btnFastForward hide";
		}
	}
}
