var rashBox, rashTxt, rashTime;
var opac;
var debugClearStr = '<a href="javascript:debugClear();" class="right">clear</a><a href="javascript:debugMarker();" class="right">marker</a><br class="clear" /><br />';

function confirmAndRedirect(message, url){
	var answer = confirm(message);
	if( answer ){window.location = url;}
}
function createPage( parent, floating, floatingType, tertiary){
	if( parent != undefined || parent != '' ){
		$('#parent').val( parent );
	}
	if( floating != undefined || floating != '' ){
		$('#floating').val( floating );
	}
	if( tertiary != undefined || tertiary != '' ){
		$('#tertiary').val( tertiary );
	}
	if( floatingType != undefined || floatingType != '' ){
		$('#floatingType').val( floatingType );
	}
	$("#newPage").dialog("open");
}


function id(x) {
	return document.getElementById(x);
}
function leadingZero(nr) {
	if (nr < 10) nr = "0" + nr;
	return nr;
}
var zindex = 12;

function zChange(x) {
	zindex++;
	document.getElementById(x).style.zIndex = zindex;
}

function trim(s) {
	while (s.substring(0, 1) == ' ') {
		s = s.substring(1, s.length);
	}
	while (s.substring(s.length - 1, s.length) == ' ') {
		s = s.substring(0, s.length - 1);
	}
	return s;
}

function pipeBreak(s) {
	var x_str = String(s);
	var ispipe;
	for (var dot = 0; dot < x_str.length; dot++) {
		if (x_str.charAt(dot) == "|") {
			ispipe = true;
			break;
		} else {
			ispipe = false;
		}
	}
	if (ispipe == true) {
		var x_arr = x_str.split("|");
		var noteStr = "";
		for (var i = 0; i < x_arr.length; i++) {
			noteStr += x_arr[i] + "\r\n";
		}
		return noteStr;
	} else {
		return x_str;
	}
}


function opacity(id, opacStart, opacEnd, millisec) {
	var speed = Math.round(millisec / 100);
	var timer = 0;
	if (opacStart > opacEnd) {
		for (i = opacStart; i >= opacEnd; i--) {
			opac = setTimeout("changeOpac(" + i + ",'" + id + "')", (timer * speed));
			timer++;
		}
	} else if (opacStart < opacEnd) {
		for (i = opacStart; i <= opacEnd; i++) {
			opac = setTimeout("changeOpac(" + i + ",'" + id + "')", (timer * speed));
			timer++;
		}
	}
}


function changeOpac(opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}


function debug(x) {
	if (document.getElementById("debug_p").innerHTML == "") {
		document.getElementById("debug_p").innerHTML = debugClearStr;
	}
	document.getElementById("debug").style.display = "block";
	document.getElementById("debug_p").innerHTML += x;
	document.getElementById("debug_p").innerHTML += "<br />";
}


function debugClear() {
	document.getElementById("debug").style.display = "none";
	document.getElementById("debug_p").innerHTML = debugClearStr;
}


function debugMarker() {
	document.getElementById("debug_p").innerHTML += '<p style="border-bottom: 1px solid #ccc;"></p>';
}


function rash(msg) {
	rashBox = document.getElementById("rashbox");
	rashTxt = document.getElementById("rashtxt");
	if (msg) {
		clearTimeout(rashTime);
		clearTimeout(opac);
		changeOpac(100, "rashbox");
		rashTxt.innerHTML = msg;
		rashBox.style.top = 180 + "px";
		rashBox.style.left = "300px";
		rashBox.style.display = "block";
		rashTime = window.setTimeout("rash()", 5000);
	} else {
		opacity("rashbox", 100, 0, 400);
	}
}


function dialogY() {
	if (IE) {
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop) {
			theTop = document.documentElement.scrollTop;
		} else if (document.body) {
			theTop = document.body.scrollTop;
		}
		return theTop + 30;
	} else {
		var dy = ((tempY - 200) > 20) ? (tempY - 200) : 20;
		return dy;
	}
}


function dialogX() {
	if (IE) {
		var theLeft;
		if (document.documentElement && document.documentElement.scrollLeft) {
			theLeft = document.documentElement.scrollLeft;
		} else if (document.body) {
			theLeft = document.body.scrollLeft;
		}
		return theLeft;
	} else {
		var dx = ((tempX - 200) > 20) ? (tempX - 200) : 20;
		return dx
	}
}


function generateID() {
	return "event_" + (parseFloat(dEvent[dEvent.length - 1][0].split("_")[1]) + 1);
}


function fracTime(x) {
	var x_str = String(x);
	var isdot = (x_str.indexOf(".") == -1) ? false : true;
	var ap;
	if (isdot == true) {
		var x_arr = x_str.split(".");
		ap = (x_str[0] < 12) ? "am" : "pm";
		if (x_arr[1]) {
			if (x_arr[1] == "0") x_arr[1] = "00";
			if (x_arr[1] == "5") x_arr[1] = "30";
			if (x_arr[1] == "25") x_arr[1] = "15";
			if (x_arr[1] == "75") x_arr[1] = "45";
			return x_arr[0] + ":" + x_arr[1];
		}
	} else {
		ap = (x_str < 12) ? "am" : "pm";
		return x_str + ":00";
	}
}


function updateTotal() {
	alert('hi');
	return false;
}


function toggle(x) {
	document.getElementById(x).style.display = document.getElementById(x).style.display == "none" ? "block" : "none";
	document.getElementById(x).blur();
}


function setValue(elementID, value) {
	document.getElementById(elementID).value = value;
}


function confirmAction(message) {
	var agree = confirm(message);
	if (agree) return true;
	else return false;
}


function catcalc(cal) {
	var date = cal.date;
	var time = date.getTime();
	var endField = document.getElementById("dateEnd");
	var startField = document.getElementById("dateStart");
	if (endField == cal.params.inputField) {
		endField = document.getElementById("dateStart");
		time -= Date.HOUR;
	} else {
		time += Date.HOUR;
	}
	var date2 = new Date(time);
	endField.value = date2.print("%Y-%m-%d %H:%M");
}


function toggleChecked(button, field) {
	if (button.value == 'Select All') {
		for (i = 0; i < field.length; i++) {
			field[i].checked = true;
		}
		button.value = 'Deselect All';
	} else {
		for (i = 0; i < field.length; i++) {
			field[i].checked = false;
		}
		button.value = 'Select All';
	}
}


function uncheckAll(field) {
	for (i = 0; i < field.length; i++) {
		field[i].checked = false;
	}
}


function checkLen(Target, tally) {
	StrLen = Target.value.length;
	if (StrLen > tally) {
		Target.value = Target.value.substring(0, tally);
		charsLeft = 0;
	} else charsLeft = tally - StrLen;
	document.getElementById("characters").innerHTML = charsLeft;
}


function goTo(page) {
	if (page != "") {
		if (page == "--") {
			resetMenu();
		} else {
			document.location.href = page;
		}
	}
	return false;
}


function resetMenu() {
	document.gmenu.page.options[0].selected = true;
}


function elementFade(elementID) {
	new Effect.Fade(document.getElementById(elementID));
}


function elementAppear(elementID) {
	new Effect.Appear(document.getElementById(elementID));
}


function validateTerms() {}


function showLoading(loadingElementID) {
	document.getElementById(loadingElementID).innerHTML = '<img src="' + base + 'images/loading/blueapple.gif" />';
}


function hideLoading(loadingElementID) {
	document.getElementById(loadingElementID).innerHTML = '';
}


function entityChange(spanID, inputSpanID) {
	var span = document.getElementById(spanID);
	span.style.display = 'none';
	var inputSpan = document.getElementById(inputSpanID);
	inputSpan.style.display = 'block';
}


function toggleUser(e) {
	if (e.value == "Username") {
		e.value = "";
    } else if (e.value == "") {}
}


function togglePass(e) {
	if (e.value == "Password") {
		e.value = "";
		id(e.id).type = "password";
	} else if (e.value == "") {
		e.type = "text";
		e.value = "Password";
	}
}


function passFocus(target_id, new_id) {
	id(target_id).innerHTML = '<input type="password" name="password" id="' + new_id + '" value="" class="loginput password" />';
	id(new_id).focus();
	id(new_id).select();
}


function passBlur() {
	id('innerPass').innerHTML = '<input type="text" name="password" id="password" value="Password" class="password required" onfocus="passFocus();" onblur="passBlur();" />';
}


function showHide(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = 'block';
	} else {
		document.getElementById(id).style.display = 'none';
	}
}


function loginDialog(state) {
	if (state == "hide") {
		id("loginPop").style.display = "none";
	} else {
		id("loginPop").style.width = "400px";
		var xtop = parseFloat(((xClientHeight() / 2) - (70)) + xScrollTop());
		xtop = (xtop > 0) ? xtop : 0;
		id("loginPop").style.top = xtop + "px";
		id("loginPop").style.left = parseFloat((xClientWidth() / 2) - 120) + "px";
		id("loginPop").style.display = "block";
	}
}


function saveStart() {
	if (debugTitles) debug("saveStart");
	id("savex").style.display = "block";
	id("savex").style.height = parseFloat(xClientHeight() + xScrollTop()) + "px";
}


function saveStop() {
	if (debugTitles) debug("saveStop");
	id("savex").style.display = "none";
}


function goToURL(url) {
	if (!url) {
		return false;
	}
	location.href = url;
	return true;
}


function includeFunc(target) {
	if (debugTitles) debug("includeFunc(" + target + ")");
	var inc = '<img id="savex" src="' + general_libary + 'images/unisite/x.gif" width="1" height="1" title="Please wait... saving changes" />';
	id(target).innerHTML += inc;
}


function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft, curtop];
}
var blurPageFlowID;

//zoneInfo
function editBox(pageFlowID, toggle) {
	$('.editBox-options').css('display', 'none');
	blurPageFlowID = pageFlowID;
	if (toggle == "show") {
		if (id("editBox-" + pageFlowID).style.display == "none") {
			id("editBox-" + pageFlowID).style.display = "block";
		} else {
			id("editBox-" + pageFlowID).style.display = "none";
		}
	} else if (toggle == "blur") {
		id("editBox-" + pageFlowID).style.display = "block";
		setTimeout('editBox(blurPageFlowID, "hide")',400);
		//window.setTimeout('document.getElementById("editBox-"+blurPageFlowID).style.display = "none";', 200);
	} else if (toggle == "hide") {
		id("editBox-" + pageFlowID).style.display = "none";
	}
}


function xScrollTop(e, bWin) {
	var offset = 0;
	if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
		var w = window;
		if (bWin && e) w = e;
		if (w.document.documentElement && w.document.documentElement.scrollTop) offset = w.document.documentElement.scrollTop;
		else if (w.document.body && xDef(w.document.body.scrollTop)) offset = w.document.body.scrollTop;
	} else {
		e = xGetElementById(e);
		if (e && xNum(e.scrollTop)) offset = e.scrollTop;
	}
	return offset;
}


function xClientHeight() {
	var v = 0,
	d = document,
	w = window;
	if ((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientHeight) {
		v = d.documentElement.clientHeight;
	} else if (d.body && d.body.clientHeight) {
		v = d.body.clientHeight;
	} else if (xDef(w.innerWidth, w.innerHeight, d.width)) {
		v = w.innerHeight;
		if (d.width > w.innerWidth) v -= 16;
	}
	return v;
}


function xClientWidth() {
	var v = 0,
	d = document,
	w = window;
	if ((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientWidth) {
		v = d.documentElement.clientWidth;
	} else if (d.body && d.body.clientWidth) {
		v = d.body.clientWidth;
	} else if (xDef(w.innerWidth, w.innerHeight, d.height)) {
		v = w.innerWidth;
		if (d.height > w.innerHeight) v -= 16;
	}
	return v;
}


function xGetElementById(e) {
	if (typeof(e) == 'string') {
		if (document.getElementById) e = document.getElementById(e);
		else if (document.all) e = document.all[e];
		else e = null;
	}
	return e;
}


function xDef() {
	for (var i = 0; i < arguments.length; ++i) {
		if (typeof(arguments[i]) == 'undefined') return false;
	}
	return true;
}


function xNum() {
	for (var i = 0; i < arguments.length; ++i) {
		if (isNaN(arguments[i]) || typeof(arguments[i]) != 'number') return false;
	}
	return true;
}


function showOnValue(showValue, value, target) {
	var targetElement = document.getElementById(target);
	if (value == showValue) {
		targetElement.style.display = 'block';
	} else {
		targetElement.style.display = 'none';
	}
}


function setLoadingMessage(targetID) {
	id(targetID).innerHTML = '<span style="padding: 2px; margin-right: 2px; background-color: red; color: white;">Loading...</span>';
}


function applyClass(id, classname) {
	document.getElementById(id).className = classname;
}


function displayLoadingIcon(targetID, msg, swicth) {
	if (swicth == true) {
		id(targetID).innerHTML = '<div class="loadingBar">' + msg + '</div>';
		id(targetID).style.display = "block";
	}
}


function getCookie(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}


function addCookie(name, value, expires, path, domain, secure) {
	expires = expires * 60 * 60 * 24 * 1000;
	var today = new Date();
	var expires_date = new Date(today.getTime() + (expires));
	var cookieString = name + "=" + escape(value) + ((expires) ? ";expires=" + expires_date.toGMTString() : "") + ((path) ? ";path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? ";secure" : "");
	document.cookie = cookieString;
}


function toggleTr(x) {
	document.getElementById(x).style.display = document.getElementById(x).style.display == "none" ? "table-row" : "none";
	document.getElementById(x).blur();
}


function hideMemberQuoteForm() {
	document.getElementById('memberquoteform').style.display = "none";
	document.getElementById('loading').innerHTML = "Please wait...Sending Mails.";
}


function validateAddLedgerEntryForm() {
	saveNewGeneralLedgerEntry();
	return true;
}


function showHidDefaultFormInputValue(e, defaultValue) {
	if (e.value == defaultValue) {
		e.value = "";
	} else if (e.value == "") {
		e.value = defaultValue;
	}
}


function outputNewGeneralLedgerEntryHTML(form) {
	if (checkForm()) {
		alert('form validated');
		alert('outputting general ledger entry on page');
		document.getElementById('newLedgerEntry').innerHTML = 'Fred Flinstone';
		return true;
	} else {
		alert('form not validated');
		return false;
	}
}


function checkForm() {
	return true;
}


function checkJumpMenus(value) {
	if (value == -1) {
		return false;
	} else {
		window.location = value;
	}
}


function checkUncheckAllSafeArray(name, value, formID) {
	var formblock = document.getElementById(formID);
	var forminputs = formblock.getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if (!forminputs[i].checked) {
				forminputs[i].checked = true;
			} else {
				forminputs[i].checked = false;
			}
		}
	}
}


function IsNumeric(strString) {
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) {
			blnResult = false;
		}
	}
	return blnResult;
}


function groupTier(route, selectName, tableName, showInfo, company) {
	var exploded = route.split(',');
  /*
  n1 = "input[id='notrecursive_"+selectName+"']";
  n2 = "input[id='"+selectName+"']";
  n3 = "input[id='roots_"+selectName+"']";
  */
  if($("input[id='notrecursive_"+selectName+"']").length>0){ //if element is set
    if($("input[id='notrecursive_"+selectName+"']").val()=='1'){ //stop recursive search in child groups.
			$("input[id='"+selectName+"']").val(exploded[exploded.length - 1]);
      updateHiddenGroupIdByGroupTier($("input[id='"+selectName+"']").val()); // This is called when hidden variable is getting updated.
      selectedRoutes = $("input[id='roots_"+selectName+"']").val().split(",");
      if(selectedRoutes.length==1)
				selectedRoutes = exploded;
      temp = new Array();
      for(x = 0; x<selectedRoutes.length-1; x++)
        temp[x] = selectedRoutes[x];
      temp[x] = $("input[id='"+selectName+"']").val();
      $("input[id='roots_"+selectName+"']").val(temp.toString());
      return;
    }
  }
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/groupTier/",
		data: "route=" + route + "&selectName=" + selectName + "&tableName=" + tableName + "&showInfo=" + showInfo + "&company=" + company+"&elementID="+$("#elementID").val()+"&"+selectName+"="+$("#"+selectName).val(),
		success: function (msg) {
			$("input[id='"+selectName+"']").val(exploded[exploded.length - 1]);
      updateHiddenGroupIdByGroupTier($("input[id='"+selectName+"']").val()); // This is called when hidden variable is getting updated.
			document.getElementById("container_" + selectName).innerHTML = msg;
			
      if($("input[id='roots_"+selectName+"']").length > 0 ){
				$("input[id='roots_"+selectName+"']").val(route);
      }
      if($("input[id='notrecursive_"+selectName+"']").val() >0){ //fill nonrecursing of group value using ajax.
        $("input[id='notrecursive_"+selectName+"']").val('1');
        routeArr = route.split(',');
        $.ajax({
          type: "POST",
          url: base2 + "search/ajax2/groupRecursion/",
          data: "groupID="+routeArr[0]+"&company="+company+"&elementID="+$("#elementID").val(),
          success: function (resp) {
            if(resp=='TRUE')
              $("input[id='notrecursive_"+selectName+"']").val('1');
            else
              $("input[id='notrecursive_"+selectName+"']").val('0');
          }
        });
      }
		}
	});
}

/*
function groupTier(route, selectName, tableName, showInfo, company) {
	var exploded = route.split(',');
  if($("#notrecursive_"+selectName).length>0){ //if element is set
    if($("#notrecursive_"+selectName).val()=='1'){ //stop recursive search in child groups.
      $("#"+selectName).val(exploded[exploded.length - 1]);
      updateHiddenGroupIdByGroupTier($("#"+selectName).val());
      selectedRoutes = $("#roots_"+selectName).val().split(",");
      if(selectedRoutes.length==1)
				selectedRoutes = exploded;
      temp = new Array();
      for(x = 0; x<selectedRoutes.length-1; x++)
        temp[x] = selectedRoutes[x];
      temp[x] = $("#"+selectName).val();
      $("#roots_"+selectName).val(temp.toString());
      return;
    }
  }
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/groupTier/",
		data: "route=" + route + "&selectName=" + selectName + "&tableName=" + tableName + "&showInfo=" + showInfo + "&company=" + company+"&elementID="+$("#elementID").val()+"&"+selectName+"="+$("#"+selectName).val(),
		success: function (msg) {
			$("#" + selectName).val(exploded[exploded.length - 1]);
      updateHiddenGroupIdByGroupTier($("#"+selectName).val());
			document.getElementById("container_" + selectName).innerHTML = msg;
      if($("#roots_"+selectName).length>0){
				$("#roots_"+selectName).val(route);
      }
      if($("#notrecursive_"+selectName).length>0){ //fill nonrecursing of group value using ajax.
        $("#notrecursive_"+selectName).val('1');
        routeArr = route.split(',');
        $.ajax({
          type: "POST",
          url: base2 + "search/ajax2/groupRecursion/",
          data: "groupID="+routeArr[0]+"&company="+company+"&elementID="+$("#elementID").val(),
          success: function (resp) {
            if(resp=='TRUE')
              $("#notrecursive_"+selectName).val('1');
            else
              $("#notrecursive_"+selectName).val('0');
          }
        });
      }
		}
	});
}
*/
function editField(label, inputType, table, field, id, action, formStuff) {
	if (action == undefined) {
		action = 'edit';
	}
	inputID = table + '_' + field + '_' + id + '_input';
	divID = table + '_' + field + '_' + id + '_div';
	if (action == 'edit') {
		$("#" + inputID).val($('#' + divID).val());
	}
	formStuff = $('#' + inputID).val();
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/editField/",
		data: "label=" + label + "&inputType=" + inputType + "&table=" + table + "&id=" + id + "&action=" + action + "&formStuff=" + formStuff + "&field=" + field,
		success: function (msg) {
			$("#" + divID).html(msg);
			if (action == 'edit') {
				$("#" + divID).addClass('ajaxEditDivOut');
			}
		}
	});
}


function sendNewsletter(numSent, siteID, newsletterID) {
	if (siteID == undefined) {
		siteID = '1';
	}
	
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/sendNewsletter/",
		data: "numSent=" + numSent + "&siteID=" + siteID + "&newsletterID=" + newsletterID,
		success: function (msg) {
			var info = msg.split(',');
			sent 		= info[0];
			carryOn = info[1];
			theID 	= info[2];
			
			if (sent && theID != 0) {
				$('#recip_' + theID).addClass('nlSuccess');
			} else {
				$('#recip_' + theID).addClass('nlFailure');
			}
			if (carryOn == '200') {
				sendNewsletter(numSent + 1, siteID, newsletterID);
			}else{
				alert('Done Sending');
			}
		}
	});
	
	
}


function reorderNav(order) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/reorderNav/",
		data: order
	});
}


function reorder3rdTier(order) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/reorder3rdTier/",
		data: order
	});
}


function jGrowl(msg) {
	if (msg != undefined) {
		$.jGrowl(msg);
	}
}


function equalHeight(group) {
	tallest = 0;
	group.each(function () {
		thisHeight = $(this).height();
		if (thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
}


function loadZoneSettings() {
	var dialogPopup = $("#zoneSettingsPopup");
	dialogPopup.dialog({
		bgiframe: true,
		modal: true,
		width: 870,
		height: 600,
		buttons: {
			Save: function () {
				saveZoneSettings();
			}
		}
	});
	dialogPopup.dialog('close');
	dialogPopup.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/zoneProperties/",
		data: "zoneInfo=" + blurZoneID,
		success: function (msg) {
			dialogPopup.html(msg);
			dialogPopup.dialog('open');
		}
	});
}


function saveZoneSettings() {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/saveZoneSettings/",
		data: $("#zone-propertyForm").serialize(),
		success: function (msg) {
			window.location = here2;
		}
	});
}


function setPageAction(id, type, pageID) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/setPageAction/",
		data: "id=" + id + '&type=' + type + '&pageID=' + pageID,
		success: function (msg) {
			window.location = here2;
		}
	});
}


function zoneAddRow(refreshPopup) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/zoneAddRow/",
		data: "zoneInfo=" + blurZoneID,
		success: function (msg) {
			if (refreshPopup == true) {
				loadZoneSettings();
			} else {
				window.location = here2;
			}
		}
	});
}


function zoneAddColumnPopup(refreshPopup, rowID) {
	var zoneSettingsPopup = $("#zoneSettingsPopup");
	zoneSettingsPopup.dialog('close');
	var zoneSettingsAddColumn = $("#zoneSettingsAddColumn");
	zoneSettingsAddColumn.dialog({
		bgiframe: true,
		modal: true,
		width: 400,
		height: 200,
		buttons: {
			Save: function () {
				zoneSettingsPopup.dialog('close');
				zoneAddColumn(refreshPopup);
			},
			Close: function () {
				if (refreshPopup) {
					window.location = here2;
				} else {
					zoneSettingsPopup.dialog('close');
				}
			}
		}
	});
	zoneSettingsAddColumn.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/zoneAddColumnHtml/",
		data: "rowID=" + rowID,
		success: function (msg) {
			zoneSettingsAddColumn.dialog('open');
			zoneSettingsAddColumn.html(msg)
			var addColumnWidth = $('#addColumnWidth');
			addColumnWidth.focus();
			addColumnWidth.bind('keypress', function (e) {
				var code = (e.keyCode ? e.keyCode : e.which);
				if (code == 13) {
					addColumnWidth.dialog('close');
					zoneAddColumn(refreshPopup);
				}
			});
		}
	});
}


function zoneAddColumn(refreshPopup) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/zoneAddColumn/",
		data: "rowID=" + $('#addColumnRowID').val() + '&width=' + $('#addColumnWidth').val(),
		success: function (msg) {
			if (refreshPopup == true) {
				loadZoneSettings();
			} else {
				window.location = here2;
			}
		}
	});
}


function zoneDeleteColumn() {
	var answer = confirm("Delete Column ?")
	if (answer) {
		$.ajax({
			type: "POST",
			url: base2 + "search/ajax2/zoneDeleteColumn/",
			data: "zoneInfo=" + blurZoneID,
			success: function (msg) {
				window.location = here2;
			}
		});
	}
}

function zoneUndoColumnDeleted(info) {
	var answer = confirm("Undo Deleted Column ?")
	if (answer) {
		$.ajax({
			type: "POST",
			url: base2 + "search/ajax2/zoneUndoColumnDeleted/",
			data: "zoneInfo=" + blurZoneID,
			success: function (msg) {
				window.location = here2;
			}
		});
	}
}

function zoneDeleteRow(info) {
	var answer = confirm("Delete Row ?")
	if (answer) {
		$.ajax({
			type: "POST",
			url: base2 + "search/ajax2/zoneDeleteRow/",
			data: "zoneInfo=" + blurZoneID,
			success: function (msg) {
				window.location = here2;
			}
		});
	}
}

function zoneUndoRowDeleted(info) {
	var answer = confirm("Undo Deleted Row ?")
	if (answer) {
		$.ajax({
			type: "POST",
			url: base2 + "search/ajax2/zoneUndoRowDeleted/",
			data: "zoneInfo=" + blurZoneID,
			success: function (msg) {
				window.location = here2;
			}
		});
	}
}

function undoPageFlowDeleted(pageFlowID) {
	var answer = confirm("Undo Deleted Element ?")
	if (answer) {
		$.ajax({
			type: "POST",
			url: base2 + "search/ajax2/undoPageFlowDeleted/",
			data: "pageFlowID=" + pageFlowID,
			success: function (msg) {
				window.location = here2;
			}
		});
	}
}

function zoneTabSettingsPopup(zoneID) {
	var zoneTabSettings = $("#zoneTabSettings");
	zoneTabSettings.dialog('close');
	zoneTabSettings.dialog({
		bgiframe: true,
		modal: true,
		width: 600,
		height: 400,
		buttons: {
			Save: function () {
				if (saveTabSettings()) {
					zoneTabSettings.dialog('close');
				}
			},
			Close: function () {
				zoneTabSettings.dialog('close');
			}
		}
	});
	zoneTabSettings.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/zoneTabSettingsHTML/",
		data: "zoneID=" + zoneID,
		success: function (msg) {
			zoneTabSettings.html(msg);
			zoneTabSettings.dialog('open');
		}
	});
}


function zoneAddTabPopup(zoneID) {
	var zoneSettingsAddTab = $("#zoneSettingsAddTab");
	zoneSettingsAddTab.dialog('close');
	zoneSettingsAddTab.dialog({
		bgiframe: true,
		modal: true,
		width: 400,
		height: 200,
		buttons: {
			Save: function () {
				zoneAddTab();
				zoneSettingsAddTab.dialog('close');
			},
			Close: function () {
				zoneSettingsAddTab.dialog('close');
			}
		}
	});
	zoneSettingsAddTab.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/zoneAddTabHTML/",
		data: "zoneID=" + zoneID,
		success: function (msg) {
			zoneSettingsAddTab.html(msg);
			zoneSettingsAddTab.dialog('open');
		}
	});
}


function zoneAddTab() {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/addZoneTab/",
		data: "zoneID=" + $('#addTabZoneID').val() + "&name=" + $('#addTabName').val(),
		success: function (msg) {
			window.location = here2;
		}
	});
}


function saveTabSettings() {
	var agree = true;
	if ($(".deleteTab:checked").val() > 0) {
		agree = false;
	}
	if (agree == false) {
		var agree = confirm('Are you Sure you want to Delete Selected ?');
	}
	if (agree) {
		$.ajax({
			type: "POST",
			url: base2 + "search/ajax2/saveTabSettings/",
			data: $("#tabsettingForm").serialize() + '&' + $("#tabOrder").sortable("serialize"),
			success: function (msg) {
				window.location = here2;
			}
		});
	} else {
		return false;
	}
}


function pasteElement(zoneID, page, pastePos, pastePosPageflow) {
	if( pastePos == undefined || pastePos == '' ){
		pastePos = '';
	}
	if( pastePosPageflow == undefined || pastePosPageflow == '' ){
		pastePos = '';
	}
	
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/pasteElement/",
		data: "zoneID=" + zoneID + "&page=" + page + '&pastePos=' + pastePos +"&pastePosPageflow=" + pastePosPageflow,
		success: function (msg) {
			if( msg == '200' ){
				window.location = here2;
			}else{
				alert(msg);
			}
		}
	});
}


function pasteZone(id, page) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/pasteZone/",
		data: "id=" + id + "&page=" + page,
		success: function (msg) {
			if (msg == '404') {
				alert('You cant mirror a zone on the same page / Paste into a zone that has Elements');
			} else {
				window.location = here2;
			}
		}
	});
}


function parentPop(state) {
	var parentSetPop = id("parentSetPop");
	if (state == "hide") {
		parentSetPop.style.display = "none";
	} else {
		parentSetPop.style.width = "280px";
		var xtop = parseFloat(((xClientHeight() / 2) - (70)) + xScrollTop());
		xtop = (xtop > 0) ? xtop : 0;
		parentSetPop.style.top = xtop + "px";
		parentSetPop.style.left = parseFloat((xClientWidth() / 2) - 120) + "px";
		parentSetPop.style.display = "block";
	}
}


function selectParent(setID) {
	$('#setID').val(setID);
	parentPop();
	$('#getParentSet').focus();
}


function createEntityPop(state) {
	var createEntityPop = id("createEntityPop");
	if (state == "hide") {
		createEntityPop.style.display = "none";
	} else {
		createEntityPop.style.width = "280px";
		var xtop = parseFloat(((xClientHeight() / 2) - (70)) + xScrollTop());
		xtop = (xtop > 0) ? xtop : 0;
		createEntityPop.style.top = xtop + "px";
		createEntityPop.style.left = parseFloat((xClientWidth() / 2) - 120) + "px";
		createEntityPop.style.display = "block";
	}
}


function createEntity(setID, pID, setName) {
	$('#setID').val(setID);
	$('#pID').val(pID);
	$('#sName').html(setName);
	$('#pName').html($('#thisEntity').html());
	$('#pName1').html($('#thisEntity').html());
	createEntityPop();
	$('#entityName').focus();
}

/*Formula editor moved to Property Edit (admin) we will eventually remove it Dt:-24-05-2010 - Nilesh*/
function loadFormulaEditor(propID, ePropID, eID, mode) {
	var FormulaEditorPopup = $("#FormulaEditorPopup");
	FormulaEditorPopup.dialog({
		bgiframe: false,
		modal: true,
		width: 600,
		height: 300,
		buttons: {
			Save: function () {
				savePropFormula();
			}
		}
	});
	FormulaEditorPopup.dialog('close');
	FormulaEditorPopup.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/formulaEditor/",
		data: ({
			formulaData: propID + '|' + ePropID + '|' + eID + '|' + mode
		}),
		success: function (msg) {
			FormulaEditorPopup.html(msg);
			FormulaEditorPopup.dialog('open');
		}
	});
}
/*Formula editor moved to Property Edit (admin) we will eventually remove it Dt:-24-05-2010 - Nilesh*/

/*Formula editor moved to Property Edit (admin) we will eventually remove it Dt:-24-05-2010 - Nilesh*/

function savePropFormula() {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/savePropFormula/",
		data: $("#propertyFormulaForm").serialize(),
		success: function (msg) {
			window.location = here2;
		}
	});
}
/*Formula editor moved to Property Edit (admin) we will eventually remove it Dt:-24-05-2010 - Nilesh*/


function loadRulesEditor(propID, mode) {
	var RulesEditorPopup = $("#RulesEditorPopup");
	RulesEditorPopup.dialog({
		bgiframe: false,
		modal: true,
		width: 600,
		height: 300,
		buttons: {
			Save: function () {
				savePropRules();
			}
		}
	});
	RulesEditorPopup.dialog('close');
	RulesEditorPopup.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/rulesEditor/",
		data: ({
			rulesData: propID + '|' + mode
		}),
		success: function (msg) {
			RulesEditorPopup.html(msg)
			RulesEditorPopup.dialog('open');
		}
	});
}


function savePropRules() {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/savePropRules/",
		data: $("#propertyRulesForm").serialize(),
		success: function (msg) {
			window.location = here2;
		}
	});
}

var blurPageFlowID;
var blurZoneID;

function editBoxMenu( button ){
	var thisObj = $( button);
	var contentHolderObj = $("#"+thisObj.attr("id")+"-holder");
	var contentInHolder  = contentHolderObj.html();
	
	$('.editBox-options:not(#'+thisObj.attr("id")+'-holder)').css("display", 'none');
	
	//Holders for last popupclicked
	if( thisObj.attr("displayType") == 'zone' ){
		blurZoneID = thisObj.attr('zoneInfo');
	}else if( thisObj.attr("displayType") == 'zoneDeleted' ){
		blurZoneID = thisObj.attr('zoneInfo');
	}else{
		blurPageFlowID = thisObj.attr('pageFlowID');
	}
	
	if( contentInHolder == null || contentInHolder == '' ){
		$.ajax({
			type: "POST",
			async: false,		
			url: base2 + "search/ajax2/ajaxContextualMenu/"+thisObj.attr("displayType"),
			data: 'pageFlowID='+thisObj.attr('pageFlowID')
			+'&pageID='+thisObj.attr('pageID')
			+'&rowID='+thisObj.attr('rowID')
			+'&zoneID='+thisObj.attr('zoneID')
			+'&zoneInfo='+thisObj.attr('zoneInfo'),
			success: function (msg) {
				contentHolderObj.html(msg);
				contentHolderObj.css("display", 'block');
			}
		});
	}else{
		if( contentHolderObj.css("display") == 'block' ){
			contentHolderObj.css("display", 'none');
		}else{
			contentHolderObj.css("display", 'block');
		}
	}
	
}


function propVal(propID) {
	return $("input[id='e_prop[" + propID + "]']").val();
}


function setFileCopyAction(id, type) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/setFileAttachmentCopyAction/",
		data: "id=" + id + '&type=' + type ,
		success: function (msg) {
			window.location = here2;
		}
	});
}

function setFilePasteAction(id, fromtable, totable, totablefield, totablefieldvalue) {
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/setFileAttachmentPasteAction/",
		data: "id=" + id + '&fromtable=' + fromtable + '&totable=' + totable + '&totablefield=' + totablefield + '&totablefieldvalue=' + totablefieldvalue ,
		success: function (msg) {
			window.location = here2;
		}
	});
}

///////////////////// Image with Popup

function loadImageWithPopupHelpText(imageWithPopupID, titlePopup) {
	var dialogPopup = $("#imgewithPopupHelpText");
  dialogPopup.dialog( 'destroy' );
	dialogPopup.dialog({
		bgiframe: true,
		modal: true,
		width: 700,
		height: 485,
    title: titlePopup
	});
	dialogPopup.dialog('close');
	dialogPopup.html('');
	$.ajax({
		type: "POST",
		url: base2 + "search/ajax2/imageWithPopupHelpText/",
		data: "imageWithPopupId=" + imageWithPopupID,
		success: function (msg) {
			dialogPopup.html(msg);
			dialogPopup.dialog('open');
		}
	});
}

/////////////////////

//Page Message System {
	function messageDialog(){
		var messageDislog = $("#pageMessages");
		messageDislog.dialog({
			bgiframe: true,
			modal: true,
			title: '',
			buttons: {
				Ok: function () {
					messageDislog.dialog('close');
				}
			}
		});
	}
//}

function multigroupSelectAll(className, obj) {
	if($(obj).text()=="Select All"){  
		$(obj).text("Deselect All");
		$("." + className).attr("checked","true");
	} else{
		$(obj).text("Select All");
		$("." + className).attr("checked","");
	}
}

function updateHiddenFieldValueForEnrtityPropertyChecboxes(obj, propertyId) {
	var checkedProperty = $(obj).attr("checked");
	if(checkedProperty){
		$("#checkboxHiddenHolder_" + propertyId).val(1);
	} else {
		$("#checkboxHiddenHolder_" + propertyId).val(0);
	}
	$('.e_prop_'+propertyId).selected( checkedProperty );
}

/* This function is useful for adding Mix Product section in Quotation */
function updateHiddenGroupIdByGroupTier(groupId) {
	if($("#checkForProductDropDown").val() != undefined) {
		productCategoryCallback(groupId);
	}
}
function setDropDown( holderID, selected, name ){
	if( selected == undefined || selected == '' ){
		selected = 0;
	}
	if( name == undefined || name == '' ){
		name = 'parentTrail[]';
	}
	$.ajax({
		type: "POST",
		url: "search/fastAjax/setDropDown",
		data: 'holderID='+holderID+'&selected='+selected+'&name='+name,
		success: function (msg) {
			if( msg != '404' ){
				$('#'+holderID).append(msg);
			}
		}
	});
}
function validatePropertyDisplayForms(formData, jqForm, options) {
	var correct 			= new Array();
	var errors 				= new Array();
	var errormsgs			= new Array();
	var formID 				= $(jqForm).attr('id');
	var entityID 			= $('#'+formID+ ' input[name=\'entityID\']').val();
	
	if( entityID == undefined || entityID == '' ){
		entityID = 0;
	}
	var propDisplayFormButton = $('.propDisplayFormButton');
	propDisplayFormButton.attr("disabled", "disabled");
	
	//Checking if required have a value....
	$('#'+formID+ ' .validate').each(function (index, domEle) {
		var currentElement  = $(this);
		var propertyID 			= currentElement.attr('propertyID');
		var propertyField   = $('[propertyID=\''+propertyID+'\']');
		
		
		if( propertyID != undefined || propertyID != '' ){
			var elementType  = propertyField.attr('type');
			
			var required = 0;
			if( propertyField.hasClass('required') ){
				required = 1;
			}
			var elementValue = '';
			switch( elementType ){
				case 'checkbox' :{
					elementValue = currentElement.attr('checked');
					if( elementValue == false ){
						elementValue = 0;
					}else{
						elementValue = 1;
					}
					break;
				}
				default :{
					elementValue = currentElement.val();
					break;
				}
			}
			
			$.ajax({
				type: 'POST',
				async: false,		
				url: 'search/fastAjax/validateProperty',
				data: 'propertyID='+propertyID+'&value='+elementValue+'&required='+required+'&entityID='+entityID,
				success: function(msg){
					if( msg != '202' ){
						errors.push(propertyID);
					}else{
						correct.push(propertyID);
					}
				}
			});
		}
	});
	//When all finished add error at same time..
	for(var i = 0; i < errors.length; i++ ){
		if( i == 0 ){
			$('#'+formID+' [propertyID=\''+errors[i]+'\']').focus();
		}
		$('#'+formID+ ' #validationMessage_'+errors[i]+'_holder').addClass('errorValidation');
		$('#'+formID+ ' #validationMessage_'+errors[i]+'_holder').css('display', 'inline');
	}
	for(var i = 0; i < correct.length; i++ ){
		$('#'+formID+ ' #validationMessage_'+correct[i]+'_holder').removeClass('errorValidation');
		$('#'+formID+ ' #validationMessage_'+correct[i]+'_holder').css('display', 'none');
	}
	
	if( errors.length > 0 ){
		alert('Please fill in the form correctly');
		propDisplayFormButton.attr("disabled", "");
		return false;
	}
	
	propDisplayFormButton.val("Sending Info ... ");
	
	
	return true;
}

//Edit in place
var previousFormObj = null;
function entityPropertyEditInPlace( obj ){
	var jqAObj = $(obj);
	
	if( previousFormObj != null ) {
		saveEntityPropertyEditInPlace( previousFormObj );
		previousFormObj = jqAObj.parent();
	}
	previousFormObj = jqAObj.parent();
	var hideValue = jqAObj.attr('hideValue') ? 1 : 0;
	
	
	$.ajax({
		type: "POST",
		async: false,
		url: "search/fastAjax/propertyEditInplace/edit",
		data: 'propID=' + jqAObj.attr('propID')+ '&entityID=' + jqAObj.attr('entityID')+ '&hideValue=' + hideValue,
		success: function(msg){
			jqAObj.removeAttr('onclick');// remove onclick which is used because of ajax ...
			jqAObj.html(msg);
			jqAObj.children().focus();
			jqAObj.unbind('click');
			previousFormObj.children('.editInPlaceSave').css('display', 'inline');
		}
	});
	return false;
}
function saveEntityPropertyEditInPlaceFromButtom( obj ){
	var jqButtonObj = $(obj);
	saveEntityPropertyEditInPlace(jqButtonObj.parent(), false);
}


function saveEntityPropertyEditInPlace( jqFormObj ){
	var jqAObj 		= jqFormObj.children('a');
	
	$.ajax({
		type: "POST",
		async: false,
		url: "search/fastAjax/propertyEditInplace/view",
		data: 'striptags=' + jqAObj.attr('striptags')+'&propID=' + jqAObj.attr('propID')+'&entityID=' + jqAObj.attr('entityID') + '&' + jqFormObj.serialize(),
		success: function(msg){
			jqFormObj.children('.editInPlaceSave').css('display', 'none');
			
			jqAObj.html(msg);
			jqAObj.click(function() { entityPropertyEditInPlace( $(this) ); }); //rebinding click..
		}
	});
}

function loadSave(propertyID, entityID, sessionIN, counter){ //Loads The save text per property
	if( sessionIN == 1 ){
		if( $('#ajax_' + propertyID  + '_save_' + counter).length ){
			$('#ajax_' + propertyID  + '_save_' + counter).html('<a href="javascript:;" onClick="saveProperty(' + propertyID + ', ' + entityID +', ' + counter +')"> [ Save ] </a>' );
		}
	}
}


//Leave at bottom of page...
$(document).ready(function () {
	//Clear System messages
	$(".delete-confirm").click(function() {  
		return confirm("Are you sure you want to delete this ? ")
	});
	
	$(".hasRules").blur(function (event) {
		if (eval(this.value + $(this).attr("rule"))) {
			return true;
		} else {
			$(this).prev("div").css('display', 'inline').fadeOut(10000);
			return false;
		}
	});
});

//Subscription {
	function subscriptionProductChildren(value, setToFindChildren, propertyID ) {
		$.ajax({ 
			type: "GET",
			url: "search/fastAjax/productSubscriptionOptions/" +setToFindChildren+ "/" +propertyID+ "/" +value,
			success: function(msg){
				$("#subscriptionProductsHolder_"+propertyID).html(msg);
		}});
	}
	
	//Load the choi
	function productSubscriptionOptionsExtraSettings(value, propertyID){
		$.ajax({ 
			type: "GET",
			url: "search/fastAjax/productSubscriptionOptionsExtraSettings/" +value+'/'+propertyID,
			success: function(msg){
				$("#subscriptionProductsExtraSettingsHolder_"+propertyID).html(msg);
			}
		});
	}
	
//}