/*
ModalBox - The pop-up window thingie with AJAX, based on prototype and script.aculo.us.

Copyright Andrey Okonetchnikov (andrej.okonetschnikow@gmail.com), 2006-2007
All rights reserved.
 
VERSION 1.6.0
Last Modified: 12/13/2007
*/
_RECORD_UPDATED_ = '<font color=\"green\">Record(s) updated successfully.</font>';
if (!window.Modalbox)
	var Modalbox = new Object();

function setDesc()
{
	var w = document.frmsection.txtName.selectedIndex;
	var selected_text = document.frmsection.txtName.options[w].text;
	alert("selected text is: "+selected_text);
	document.frmsection.txtDescription = selected_text;
}


function checkEnter(e,id){ //e is event object passed from function invocation,id lets us know if its from the merchant site (0) or user (order id)
    var characterCode; //literal character code will be stored in this variable
    if (e && e.which) { //if which property of event object is supported (NN4)
        e = e;
        characterCode = e.which; //character code is contained in NN4's which property
    }
    else {
        e = event;
        characterCode = e.keyCode; //character code is contained in IE's keyCode property
    }
    
    if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
    	if (id == 0)
    		fnCheckFavorite_site(); //call the validation script
		else
	    	fnCheckFavorite(id); //call the validation script		
		return false;
    }
    else {
        return true;
    }
}


function mvalidateEmail()
{
	/***************** Browser ******************/
	var http = null;
	var isOpera=navigator.userAgent.indexOf('Opera')>-1;
	var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
	var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
		
	if(isIE)
		http = new ActiveXObject("Microsoft.XMLHTTP");
	else if(isMoz)
		http = new XMLHttpRequest();
	/***************** Browser ******************/
	if(is_empty(document.frmmid.merchant_email_pass, "Merchant Email"))
	{
		document.frmmid.merchant_email_pass.focus();
		return false;
	}
	else
	{
		var mailid=document.frmmid.merchant_email_pass.value;
		var url = "ajx_forgot_password.php?act=MSEND_PASSWORD&emailid="+mailid;
		var randomno = parseInt(Math.random()*99999999);  // cache buster	
		url=url + "&rand=" + randomno;
		http.open("GET", url, false);
		http.send(null);
		var chval=http.responseText;
		if (http.readyState == 4) {
			document.getElementById("fpassword").innerHTML=chval;
			document.frmmid.merchant_email_pass.value="";
			//Modalbox.hide();
		}		
		/*document.frmmid.page_action.value="MSEND_PASSWORD";
		document.frmmid.submit();
		return true;*/
	}
}
function validateEmail()
{
	//alert("starting validate email");
	/***************** Browser ******************/
	var http = null;
	var isOpera=navigator.userAgent.indexOf('Opera')>-1;
	var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
	var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
		
	if(isIE)
		http = new ActiveXObject("Microsoft.XMLHTTP");
	else if(isMoz)
		http = new XMLHttpRequest();
	/***************** Browser ******************/
	if(is_empty(document.frmuid.user_email_pass, "User Email"))
	{
		document.frmuid.user_email_pass.focus();
		return false;
	}
	else
	{
		var mailid=document.frmuid.user_email_pass.value;
		var url = "ajx_forgot_password.php?act=SEND_PASSWORD&emailid="+mailid;
		var randomno = parseInt(Math.random()*99999999);  // cache buster	
		url=url + "&rand=" + randomno;
		http.open("GET", url, false);
		http.send(null);
		var chval=http.responseText;
		if (http.readyState == 4) {
			document.getElementById("fpassword").innerHTML=chval;
			document.frmuid.user_email_pass.value="";
			//Modalbox.hide();
		}
		
		/*document.frmuid.page_action.value="SEND_PASSWORD";
		document.frmuid.submit();
		return true;*/
	}
}
function fnpwindowclose()
{
	Modalbox.hide();
}

function validate_leadtime(obj)
{
	// ****arosenthal****
	//alert("bypassing xxxxxxxxxxx validate lead time in modalbox.js  *amr*");
	return true;
	// **** end arosenthal ****
	num = obj.value;
	if(num >= 10 && num <= 60)
    {
		//document.getElementById('lead_time_emsg').innerHTML = "";
       return true;
    }
    else
    {
       alert ("Lead Time should be between 10 to 60");
	   return false;
    }
}
function validatefield(field) {

	if (field.value.indexOf(" ") > -1) {
		alert("Invalid Entry!  No Spaces Allowed");
		field.focus();
		field.select();
		return false;	
	}
	var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	var ok = "yes";
	var temp;
	for (var i=0; i<field.value.length; i++) {
		temp = "" + field.value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") 
			ok = "no";
	}
	if (ok == "no") {
		alert("Invalid entry!  Only alpha numeric characters are accepted!");
		field.focus();
		field.select();
		return false;
   }
   return true;
}
function Validatedecimalf(Field) {
strValidChars = "0123456789.-";
 formField = Field.value;
	for (i = 0; i < formField.length ; i++)
	{
	strChar = formField.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
			{
			alert ("please enter valid decimal number");					
			return false;
			}
	}
	if (!/^\d+(\.\d+)?$/.test(formField)) {
		//alert("please enter valid decimal number");				
			alert ("please enter valid decimal number");					
			return false;
	}
formField  = parseFloat(formField);
Field.value = formField.toFixed(5);
return true;
}
function fnCheckFavorite(o_id)
{
	
	if(is_empty(document.frmFavorite.txtName, "Favorite Name"))
	{
		document.frmFavorite.txtName.focus();
		return false;
	}
	if(document.frmFavorite.txtName.value.length  > 20)
	{
		alert(" Maximum 20 characters are accepted!");
		document.frmFavorite.txtNam.focus();		
		return false;
	}
	// added by *** arosenthal ***   need to disallow spaces so we can add lead time for SMS in message body
	if (document.frmFavorite.txtName.value.indexOf(" ") > -1 )
	{
		alert("Name cannot contain any spaces");
		return false;
	}
	if(!validatefield(document.frmFavorite.txtName))
	{
		return false;
	}
	if(is_empty(document.frmFavorite.txtLeadtime, "Lead Time"))
	{
		document.frmFavorite.txtLeadtime.focus();
		return false;
	}	
	if(!(validate_leadtime(document.frmFavorite.txtLeadtime)))
	{	
		document.frmFavorite.txtLeadtime.focus();
			return false;
	}	
/*  *** not using tip amount arosenthal ***
	if(document.frmFavorite.txtTipamt.value == "")
	{
		document.frmFavorite.txtTipamt.value = 0;		
	}
	if(!Validatedecimalf(document.frmFavorite.txtTipamt))
	{
		document.frmFavorite.txtTipamt.focus();
		return false;
	}
*/
	else
	{
		/***************** Browser ******************/
		var http = null;
		var isOpera=navigator.userAgent.indexOf('Opera')>-1;
		var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
		var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
			
		if(isIE)
			http = new ActiveXObject("Microsoft.XMLHTTP");
		else if(isMoz)
			http = new XMLHttpRequest();
		/***************** Browser ******************/
		var fname=document.frmFavorite.txtName.value;
		var fleadtime=document.frmFavorite.txtLeadtime.value;
		var ftipamt=document.frmFavorite.txtTipamt.value;

		//var fnote=document.frm.Merchant_Note.value;
		//alert("note removed");
		
		// **** arosenthal ****  added for order amount but NOT USING for now
		var fordamt=document.frmFavorite.txtOrdAmt.value;
		
		var urlc = "setFavorite.php?task=SUBMIT&order_id="+o_id+"&fname="+fname+"&fleadtime="+fleadtime+"&ftipamt="+ftipamt+"&fordamt="+fordamt;	
	
		var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
		urlc=urlc + "&rand=" + randomnoc;
		http.open("GET", urlc, false);
		http.send(null);
		var chval=http.responseText;
		chval = chval.replace("sms_sent", "");
		alert (chval);
		if(chval!='')
		{			
			//alert (chval.substring(0,14));
			//if(	chval.substring(0,14) == "Favorite Added")	
			if (chval.indexOf("Favorite Added") > -1)
				Modalbox.hide();
		}
	}
}

function fnCheckFavorite_site()
{
	//alert("in the fnCheckFavorite_site() in modalbox.js");
	if(is_empty(document.frmFavorite.txtName, "Favorite Name"))
	{
		document.frmFavorite.txtName.focus();
		return false;
	}
	if(document.frmFavorite.txtName.value.length  > 20)
	{
		alert(" Maximum 20 characters are accepted!");
		document.frmFavorite.txtNam.focus();		
		return false;
	}
	if(!validatefield(document.frmFavorite.txtName))
	{
		return false;
	}
	if(is_empty(document.frmFavorite.txtLeadtime, "Lead Time"))
	{
		document.frmFavorite.txtLeadtime.focus();
		return false;
	}	
	if(!(validate_leadtime(document.frmFavorite.txtLeadtime)))
	{	
		document.frmFavorite.txtLeadtime.focus();
			return false;
	}	
	document.frmFavorite.txtTipamt.value = document.frm.tip.value;
	
	if(document.frmFavorite.txtTipamt.value == "")
	{
		document.frmFavorite.txtTipamt.value = 0;		
	}
	if(!Validatedecimalf(document.frmFavorite.txtTipamt))
	{
		document.frm.tip.focus();
		return false;
	}
	else
	{
		/***************** Browser ******************/
		var http = null;
		var isOpera=navigator.userAgent.indexOf('Opera')>-1;
		var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
		var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
			
		if(isIE)
			http = new ActiveXObject("Microsoft.XMLHTTP");
		else if(isMoz)
			http = new XMLHttpRequest();
		/***************** Browser ******************/
		var fname=document.frmFavorite.txtName.value;
		var fleadtime=document.frmFavorite.txtLeadtime.value;
		var ftipamt=document.frmFavorite.txtTipamt.value;
		
		// ****arosenthal**** adding note capability to the favorite functionality (what a concept!)  sheesh!  who wrote this crap?
		var fnote=document.frm.Merchant_Note.value;
		//alert("fnote: " + fnote);
		
		var urlc = "setmFavorite.php?task=SUBMIT&fname="+fname+"&fleadtime="+fleadtime+"&ftipamt="+ftipamt+"&fnote="+fnote;	
	
		var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
		urlc=urlc + "&rand=" + randomnoc;
		//alert(urlc);return false;
		http.open("GET", urlc, false);
		http.send(null);
		var chval=http.responseText;
		chval = chval.replace("sms_sent", "");
		alert (chval);
		if(chval!='')
		{			
			//document.frm.hdnsecids.value="";			
			//alert (chval.substring(0,14));
			//if(	chval.substring(0,14) == "Favorite Added")	
			if (chval.indexOf("Favorite Added") > -1)
				Modalbox.hide();
		}
	}
}

function fnCheckFavorite_edit()
{
	if(is_empty(document.frmFavorite.txtName, "Favorite Name"))
	{
		document.frmFavorite.txtName.focus();
		return false;
	}
	if(document.frmFavorite.txtName.value.length  > 20)
	{
		alert(" Maximum 20 characters are accepted!");
		document.frmFavorite.txtNam.focus();		
		return false;
	}
	if(!validatefield(document.frmFavorite.txtName))
	{
		return false;
	}
	if(is_empty(document.frmFavorite.txtLeadtime, "Lead Time"))
	{
		document.frmFavorite.txtLeadtime.focus();
		return false;
	}	
	if(!(validate_leadtime(document.frmFavorite.txtLeadtime)))
	{	
		document.frmFavorite.txtLeadtime.focus();
			return false;
	}	
	document.frmFavorite.txtTipamt.value = document.frm.tip.value;
	
	if(document.frmFavorite.txtTipamt.value == "")
	{
		document.frmFavorite.txtTipamt.value = 0;		
	}
	if(!Validatedecimalf(document.frmFavorite.txtTipamt))
	{
		document.frm.tip.focus();
		return false;
	}
	else
	{
		/***************** Browser ******************/
		var http = null;
		var isOpera=navigator.userAgent.indexOf('Opera')>-1;
		var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
		var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
			
		if(isIE)
			http = new ActiveXObject("Microsoft.XMLHTTP");
		else if(isMoz)
			http = new XMLHttpRequest();
		/***************** Browser ******************/
		var fname=document.frmFavorite.txtName.value;
		var fleadtime=document.frmFavorite.txtLeadtime.value;
		var ftipamt=document.frmFavorite.txtTipamt.value;
		
		var urlc = "editremoveItem.php?task=SAVEFAVORITE&fname="+fname+"&fleadtime="+fleadtime+"&ftipamt="+ftipamt;	
	
		var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
		urlc=urlc + "&rand=" + randomnoc;
		//alert(urlc);return false;
		http.open("GET", urlc, false);
		http.send(null);
		var chval=http.responseText;
		alert (chval);
		if(chval!='')
		{			
			//document.frm.hdnsecids.value="";			
			//Modalbox.hide();
		}
	}
}

function fnCheckSec(m_id,p_action)
{
	if(is_empty(document.frmsection.txtName, "Name"))
	{
		document.frmsection.txtName.focus();
		return false;
	}
	if(is_empty(document.frmsection.txtDescription, "Description"))
	{
		document.frmsection.txtDescription.focus();
		return false;		
	}
	else
	{
		/***************** Browser ******************/
		var http = null;
		var isOpera=navigator.userAgent.indexOf('Opera')>-1;
		var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
		var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
			
		if(isIE)
			http = new ActiveXObject("Microsoft.XMLHTTP");
		else if(isMoz)
			http = new XMLHttpRequest();
		/***************** Browser ******************/
		//var w = document.frmsection.txtName.selectedIndex;
		//var secname = document.frmsection.txtName.options[w].text;		
		//var secvalue=document.frmsection.txtName.value;
		var secname=document.frmsection.txtName.value;
		var secdesc=document.frmsection.txtDescription.value;
		if(p_action=="SAVE_SECTION"){
			is_publish = fnchkpublish(m_id);
			if(is_publish=='Y')
				if(!confirm("\t\t\t::W A R N I N G::\nAll changes will effect immediately on your website."))
					return false;
				var urlc = "setsection.php?task=Add&id=1&page_action="+p_action+"&merchant_id="+m_id+"&secname="+secname+"&secdesc="+secdesc; //+"&secvalue="+secvalue;	
		}
		else if(p_action=="EDIT_SECTION"){
			is_publish = fnchkpublish(m_id);
			if(is_publish=='Y')
				if(!confirm("\t\t\t::W A R N I N G::\nAll changes will effect immediately on your website."))
					return false;
			var sid=document.frmsection.sid.value;
			var urlc = "setsection.php?task=Edit&id=1&page_action="+p_action+"&merchant_id="+m_id+"&secname="+secname+"&secdesc="+secdesc+"&sid="+sid;//+"&secvalue="+secvalue;
		}
		var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
		urlc=urlc + "&rand=" + randomnoc;
		http.open("GET", urlc, false);
		http.send(null);
		var chval=http.responseText;
		if(chval!='')
		{
			document.getElementById("sec_menu").innerHTML=chval;
			document.frm.hdnsecids.value="";
			document.getElementById('scmsg').innerHTML=_RECORD_UPDATED_;
			Modalbox.hide();
		}
	}
}
function fnCheckSize(m_id,p_action)
{
	if(is_empty(document.frmsection.sizename, "Size"))
	{
		document.frmsection.sizename.focus();
		return false;
	}
	if(is_empty(document.frmsection.sizedesc, "Description"))
	{
		document.frmsection.sizedesc.focus();
		return false;
	}
	else
	{
		/***************** Browser ******************/
		var http = null;
		var isOpera=navigator.userAgent.indexOf('Opera')>-1;
		var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
		var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
			
		if(isIE)
			http = new ActiveXObject("Microsoft.XMLHTTP");
		else if(isMoz)
			http = new XMLHttpRequest();
		/***************** Browser ******************/
		var secid=document.frmsection.sizesection.value;
		var sizename=document.frmsection.sizename.value;
		var sizedesc=document.frmsection.sizedesc.value;
		if(p_action=="SAVE_SIZE"){
			is_publish = fnchkpublish(m_id);
			if(is_publish=='Y')
				if(!confirm("\t\t\t::W A R N I N G::\nAll changes will effect immediately on your website."))
					return false;
			var urlc = "setsection.php?task=Add&id=2&page_action="+p_action+"&merchant_id="+m_id+"&secid="+secid+"&sizename="+sizename+"&sizedesc="+sizedesc;	
		}
		else if(p_action=="EDIT_SIZE"){
			var sid=document.frmsection.sid.value;
			is_publish = fnchkpublish(m_id);
			if(is_publish=='Y')
				if(!confirm("\t\t\t::W A R N I N G::\nAll changes will effect immediately on your website."))
					return false;
			var urlc = "setsection.php?task=Edit&id=2&page_action="+p_action+"&merchant_id="+m_id+"&secid="+secid+"&sizename="+sizename+"&sizedesc="+sizedesc+"&sid="+sid;	
		}
		
		var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
		urlc=urlc + "&rand=" + randomnoc;
		http.open("GET", urlc, false);
		http.send(null);
		var chval=http.responseText;
		if(chval!='')
		{
			document.getElementById("size_menu").innerHTML=chval;
			document.frm.hdnsizeids.value="";
			document.getElementById('szmsg').innerHTML=_RECORD_UPDATED_;
			Modalbox.hide();
		}
	}
}
function fnCheckItems1(m_id,p_action)
{
	if(is_empty(document.frmsection.itemname, "Item Name"))
	{
		document.frmsection.itemname.focus();
		return false;
	}
	if(is_empty(document.frmsection.itemdesc, "Description"))
	{
		document.frmsection.itemdesc.focus();
		return false;
	}
	else
	{
		/***************** Browser ******************/
		var http = null;
		var isOpera=navigator.userAgent.indexOf('Opera')>-1;
		var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
		var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
			
		if(isIE)
			http = new ActiveXObject("Microsoft.XMLHTTP");
		else if(isMoz)
			http = new XMLHttpRequest();
		/***************** Browser ******************/
		var secid=document.frmsection.itemsection.value;
		var itemname=document.frmsection.itemname.value;
		var itemdesc=document.frmsection.itemdesc.value;

		p_ids = document.getElementById('priceids').value;
			if(p_ids != "")
				{
					res_prices = fetch_size_prices(p_ids);
				}
				else
				{
					res_prices = "null";
				}
		//return false;
		alert(res_prices);
		if(p_action=="SAVE_ITEM"){
			is_publish = fnchkpublish(m_id);
			if(is_publish=='Y')
				if(!confirm("\t\t\t::W A R N I N G::\nAll changes will effect immediately on your website."))
					return false;
			var urlc = "setsection.php?task=Add&id=3&page_action="+p_action+"&merchant_id="+m_id+"&secid="+secid+"&itemname="+itemname+"&itemdesc="+itemdesc;		
		}
		else if(p_action=="EDIT_ITEM"){
			var sid=document.frmsection.sid.value;
			is_publish = fnchkpublish(m_id);
			if(is_publish=='Y')
				if(!confirm("\t\t\t::W A R N I N G::\nAll changes will effect immediately on your website."))
					return false;
			var urlc = "setsection.php?task=Edit&id=3&page_action="+p_action+"&merchant_id="+m_id+"&secid="+secid+"&itemname="+itemname+"&itemdesc="+itemdesc+"&sid="+sid;	
		}
		var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
		urlc=urlc + "&rand=" + randomnoc;
		http.open("POST", urlc, false);

		http.send(res_prices);

		var chval=http.responseText;
		
		if(chval!='')
		{alert(chval);
			document.getElementById("items_menu").innerHTML=chval;
			document.frm.hdnitemids.value="";
			document.getElementById('immsg').innerHTML=_RECORD_UPDATED_;
			Modalbox.hide();
		}
	}
}


function fnCheckItems(m_id,p_action) {
	if(is_empty(document.frmsection.itemname, "Item Name"))
	{
		document.frmsection.itemname.focus();
		return false;
	}
	if(is_empty(document.frmsection.itemdesc, "Description"))
	{
		document.frmsection.itemdesc.focus();
		return false;
	}
	
		/***************** Browser ******************/
		var secid=document.frmsection.itemsection.value;
		var itemname=document.frmsection.itemname.value;
		var itemdesc=document.frmsection.itemdesc.value;
		var allowmods=document.frmsection.allow_mods.value;
		
		var type = "";
		if (document.frmsection.mtype) {
			var type=document.frmsection.mtype.value;
		}
		
		

    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
		
		p_ids = document.getElementById('priceids').value;
	
			if(p_ids != "")
				{
					poststr = fetch_size_prices(p_ids);
					
					if(poststr == 0)
						return false;
				}
				else
				{
					poststr = "null";
				}	 

	   if(p_action=="SAVE_ITEM"){
			var strURL = "setsection.php?task=Add&id=3&page_action="+p_action+"&merchant_id="+m_id+"&secid="+secid+"&itemname="+itemname+"&itemdesc="+itemdesc+"&allow_mods="+allowmods;		
		}
		else if(p_action=="EDIT_ITEM"){
			var sid=document.frmsection.sid.value;
			var strURL = "setsection.php?task=Edit&id=3&page_action="+p_action+"&merchant_id="+m_id+"&secid="+secid+"&itemname="+itemname+"&itemdesc="+itemdesc+"&allow_mods="+allowmods+"&sid="+sid+"&mtype="+type;	
		}
	//alert(strURL);
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
			
				//alert(self.xmlHttpReq.responseText);
				chval = self.xmlHttpReq.responseText;
				document.getElementById("items_menu").innerHTML=chval;
				document.frm.hdnitemids.value="";
				document.getElementById('immsg').innerHTML=_RECORD_UPDATED_;
				Modalbox.hide();
		
        }
    }
    self.xmlHttpReq.send(poststr);
//self.xmlHttpReq.send(null);
}

function addModItems()
{
	var merchant_id=document.modform.merchant_id.value;
	var modifier_items_string=document.modform.modifier_items_string.value;
	var modifier_id=document.modform.modifier_id.value;
	var strURL = "utilities/add_modifier_item.php?merchant_id="+merchant_id+"&modifier_items_string="+modifier_items_string+"&modifier_id="+modifier_id;
	//alert("url: "+strURL);
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
	   self.xmlHttpReq.open('POST', strURL, true);
	    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    self.xmlHttpReq.onreadystatechange = function() {
	        if (self.xmlHttpReq.readyState == 4) {
				
					//alert(self.xmlHttpReq.responseText);
					//chval = self.xmlHttpReq.responseText;
					//document.getElementById("mods_menu").innerHTML=chval;
					//document.frm.hdnitemids.value="";
					document.getElementById('immsg').innerHTML=_RECORD_UPDATED_;
					Modalbox.hide();
			
	        }
	    };
	    self.xmlHttpReq.send(null);
}

function addMod()
{
	var merchant_id=document.modform.merchant_id.value;
	var menu_type_id=document.modform.menu_type_id.value;
	var modifier_name=document.modform.modifier_name.value;
	var max_count=document.modform.max_count.value;
	var exclusive_list=document.modform.exclusive_list.value;
	var modifier_description=document.modform.modifier_description.value;
	var modifier_items_string=document.modform.modifier_items_string.value;
	var strURL = "utilities/load_merchant_mods.php?merchant_id="+merchant_id+"&menu_type_id="+menu_type_id+""+"&modifier_name="+modifier_name+"&max_count="+max_count+"&exclusive_list="+exclusive_list+"&modifier_description="+modifier_description+"&modifier_items_string="+modifier_items_string;	
	//alert("url: "+strURL);
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
	   self.xmlHttpReq.open('POST', strURL, true);
	    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    self.xmlHttpReq.onreadystatechange = function() {
	        if (self.xmlHttpReq.readyState == 4) {
				
					//alert(self.xmlHttpReq.responseText);
					//chval = self.xmlHttpReq.responseText;
					//document.getElementById("mods_menu").innerHTML=chval;
					//document.frm.hdnitemids.value="";
					document.getElementById('immsg').innerHTML=_RECORD_UPDATED_;
					Modalbox.hide();
			
	        }
	    };
	    self.xmlHttpReq.send(null);
}

function fnCheckMods(m_id,p_action) {
		/***************** Browser ******************/
		var secid=document.frmsection.itemsection.value;
		var mod=document.frmsection.mods.value;
		var mod_item=document.frmsection.mod_items.value;
		
		var type = "";
		if (document.frmsection.mtype) {
			var type=document.frmsection.mtype.value;
		}
		
		

    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
		
		p_ids = document.getElementById('priceids').value;
	
			if(p_ids != "")
				{
					poststr = fetch_size_prices(p_ids);
					
					if(poststr == 0)
						return false;
				}
				else
				{
					poststr = "null";
				}	 

	   if(p_action=="SAVE_MOD_PRICE"){
			var strURL = "setsection.php?task=Add&id=4&page_action="+p_action+"&merchant_id="+m_id+"&menu_type_id="+secid+"&mod_id="+mod+"&mod_item_id="+mod_item;		
		}
		else if(p_action=="EDIT_MOD_PRICE"){
			var sid=document.frmsection.sid.value;
			var strURL = "setsection.php?task=Edit&id=4&page_action="+p_action+"&merchant_id="+m_id+"&mod_id="+mod+"&mod_item_id="+mod_item;	
		}
	//alert(strURL);
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
			
				//alert(self.xmlHttpReq.responseText);
				chval = self.xmlHttpReq.responseText;
				document.getElementById("mods_menu").innerHTML=chval;
				document.frm.hdnitemids.value="";
				document.getElementById('immsg').innerHTML=_RECORD_UPDATED_;
				Modalbox.hide();
		
        }
    }
    self.xmlHttpReq.send(poststr);
//self.xmlHttpReq.send(null);
}

function Validate_decimal(str) {
strValidChars = "0123456789.-";
 formField =  document.getElementById(str).value;


	for (k = 0; k < formField.length ; k++)
	{
	strChar = formField.charAt(k);
		if (strValidChars.indexOf(strChar) == -1)
			{
			alert('please enter valid decimal number');
			document.getElementById(str).focus();
			if (document.getElementById(str+"_lable") != null)
			{
				document.getElementById(str+"_lable").style.color = 'red';	
			}
			
			if (document.getElementById(str+"_emsg") != null)
			{
				document.getElementById(str+"_emsg").innerHTML = "please enter valid decimal number";
			}
					
			return false;
			}

	}
	if (!/^\d+(\.\d+)?$/.test(formField)) {
		alert("please enter valid decimal number");
		document.getElementById(str).focus();

		if (document.getElementById(str+"_lable") != null)
			{
				document.getElementById(str+"_lable").style.color = 'red';	
			}
			
			if (document.getElementById(str+"_emsg") != null)
			{
				document.getElementById(str+"_emsg").innerHTML = "please enter valid decimal number";
			}
	return false;
	}
formField  = parseFloat(formField);
document.getElementById(str).value = formField.toFixed(5);
return true;
}

//function for fetch prices of items
function fetch_size_prices(str)
{
	res_str = "";
	var mytool_array=str.split(",");		
	i = 0;
	while (i < mytool_array.length)
	 {
	 // alert(mytool_array[i]);
	  id = mytool_array[i];
		if(mytool_array.length == 1)
			{
			default_id =  document.frmsection.d_size.value;	
			}
		 else
		  if (document.frmsection.d_size[i].checked)
		   {
			default_id =  document.frmsection.d_size[i].value;	
		   }

			activeid = 'active_'+id;
		   if (document.getElementById(activeid).checked)		  
				active_id =  1;			  
		   else
				active_id =  0;	
	 
		// active_id =  document.getElementById('active_'+id).value;
		
		 if(Validate_decimal('price_'+id) == false)		
			 return 0;
		
		 price_id =  document.getElementById('price_'+id).value;
			
		// alert(default_id +"-"+ active_id +"-"+ price_id);
		 if (i == 0)
		 {
			  res_str = "active_"+id+"="+active_id + "&price_"+id+"="+document.getElementById('price_'+id).value;
		 }
		else
		 {
			 res_str += "&active_"+id+"="+active_id + "&price_"+id+"="+document.getElementById('price_'+id).value;
		 }
		 
	   i = i+1;
	  }
	res_str =  res_str+"&default_id="+default_id+"&priceids="+str;
	
	return res_str;
	
}


//function for display sizes for selected section
function get_sizes(obj)
{	
		//alert("sec id: "+obj.value);
		var http = null;
				var isOpera=navigator.userAgent.indexOf('Opera')>-1;
				var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
				var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
					
				if(isIE)
					http = new ActiveXObject("Microsoft.XMLHTTP");
				else if(isMoz)
					http = new XMLHttpRequest();
				/***************** Browser ******************/
				var sec_id=obj.value;
				
				
				var urlc = "setsection.php?task=GET_SIZES&sec_id="+sec_id;	
				
				var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
				urlc=urlc + "&rand=" + randomnoc;
				http.open("GET", urlc, false);
				
				http.send(null);
				var chval=http.responseText;
				if(chval!='')
				{	//alert(chval);
					//document.getElementById('itemdesc').value = chval;					
					document.getElementById('item_section_sizes').innerHTML=chval;
					Modalbox.resizeToContent();
				}

}

function get_modifiers(obj)
{
	var http = null;
	var isOpera=navigator.userAgent.indexOf('Opera')>-1;
	var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
	var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
		
	if(isIE)
		http = new ActiveXObject("Microsoft.XMLHTTP");
	else if(isMoz)
		http = new XMLHttpRequest();
	/***************** Browser ******************/
	var sec_id=obj.value;
	
	
	var urlc = "setsection.php?task=GET_MODS&sec_id="+sec_id;	
	
	var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
	urlc=urlc + "&rand=" + randomnoc;
	http.open("GET", urlc, false);
	
	http.send(null);
	var chval=http.responseText;
	if(chval!='')
	{	//alert(chval);
		//document.getElementById('itemdesc').value = chval;					
		document.getElementById('mod_list').innerHTML=chval;
		Modalbox.resizeToContent();
	}
}
function get_modifier_items(obj)
{
	var http = null;
	var isOpera=navigator.userAgent.indexOf('Opera')>-1;
	var isIE=navigator.userAgent.indexOf('MSIE')>1&&!isOpera;
	var isMoz=navigator.userAgent.indexOf('Mozilla/5.')==0&&!isOpera;
		
	if(isIE)
		http = new ActiveXObject("Microsoft.XMLHTTP");
	else if(isMoz)
		http = new XMLHttpRequest();
	/***************** Browser ******************/
	var modifier_id=obj.value;
	
	
	var urlc = "setsection.php?task=GET_MOD_ITEMS&modifier_id="+modifier_id;	
	
	var randomnoc = parseInt(Math.random()*99999999);  // cache buster	
	urlc=urlc + "&rand=" + randomnoc;
	http.open("GET", urlc, false);
	
	http.send(null);
	var chval=http.responseText;
	if(chval!='')
	{	//alert(chval);
		//document.getElementById('itemdesc').value = chval;					
		document.getElementById('mod_item_list').innerHTML=chval;
		Modalbox.resizeToContent();
	}
}



Modalbox.Methods = {
	overrideAlert: false, // Override standard browser alert message with ModalBox
	focusableElements: new Array,
	currFocused: 0,
	initialized: false,
	active: true,
	options: {
		title: "SplickIt", // Title of the ModalBox window
		overlayClose: false, // Close modal box by clicking on overlay
		width: 500, // Default width in px
		height: 90, // Default height in px
		overlayOpacity: .65, // Default overlay opacity
		overlayDuration: .25, // Default overlay fade in/out duration in seconds
		slideDownDuration: .5, // Default Modalbox appear slide down effect in seconds
		slideUpDuration: .5, // Default Modalbox hiding slide up effect in seconds
		resizeDuration: .25, // Default resize duration seconds
		inactiveFade: true, // Fades MB window on inactive state
		transitions: true, // Toggles transition effects. Transitions are enabled by default
		loadingString: "Please wait. Loading...", // Default loading string message
		closeString: "Close window", // Default title attribute for close window link
		closeValue: "&times;", // Default string for close link in the header
		params: {},
		method: 'get', // Default Ajax request method
		autoFocusing: true, // Toggles auto-focusing for form elements. Disable for long text pages.
		aspnet: false // Should be use then using with ASP.NET costrols. Then true Modalbox window will be injected into the first form element.
	},
	_options: new Object,
	
	setOptions: function(options) {
		Object.extend(this.options, options || {});
	},
	
	_init: function(options) {
		// Setting up original options with default options
		Object.extend(this._options, this.options);
		this.setOptions(options);
		
		//Create the overlay
		this.MBoverlay = new Element("div", { id: "MB_overlay", opacity: "0" });
		
		//Create DOm for the window
		this.MBwindow = new Element("div", {id: "MB_window", style: "display: none"}).update(
			this.MBframe = new Element("div", {id: "MB_frame"}).update(
				this.MBheader = new Element("div", {id: "MB_header"}).update(
					this.MBcaption = new Element("div", {id: "MB_caption"})
				)
			)
		);
		this.MBclose = new Element("a", {id: "MB_close", title: this.options.closeString, href: "#"}).update("<span>" + this.options.closeValue + "</span>");
		this.MBheader.insert({'bottom':this.MBclose});
		
		this.MBcontent = new Element("div", {id: "MB_content"}).update(
			this.MBloading = new Element("div", {id: "MB_loading"}).update(this.options.loadingString)
		);
		this.MBframe.insert({'bottom':this.MBcontent});
		
		// Inserting into DOM. If parameter set and form element have been found will inject into it. Otherwise will inject into body as topmost element.
		// Be sure to set padding and marging to null via CSS for both body and (in case of asp.net) form elements. 
		var injectToEl = this.options.aspnet ? $(document.body).down('form') : $(document.body);
		injectToEl.insert({'top':this.MBwindow});
		injectToEl.insert({'top':this.MBoverlay});
		
		// Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
		this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
		this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		
		//Adding event observers
		this.hideObserver = this._hide.bindAsEventListener(this);
		this.kbdObserver = this._kbdHandler.bindAsEventListener(this);
		this._initObservers();

		this.initialized = true; // Mark as initialized
	},
	
	show: function(content, options) {
		if(!this.initialized) this._init(options); // Check for is already initialized
		
		this.content = content;
		this.setOptions(options);
		
		if(this.options.title) // Updating title of the MB
			$(this.MBcaption).update(this.options.title);
		else { // If title isn't given, the header will not displayed
			$(this.MBheader).hide();
			$(this.MBcaption).hide();
		}
		
		if(this.MBwindow.style.display == "none") { // First modal box appearing
			this._appear();
			this.event("onShow"); // Passing onShow callback
		}
		else { // If MB already on the screen, update it
			this._update();
			this.event("onUpdate"); // Passing onUpdate callback
		} 
	},
	
	hide: function(options) { // External hide method to use from external HTML and JS
		if(this.initialized) {
			// Reading for options/callbacks except if event given as a pararmeter
			if(options && typeof options.element != 'function') Object.extend(this.options, options); 
			// Passing beforeHide callback
			this.event("beforeHide");
			if(this.options.transitions)
				Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, transition: Effect.Transitions.sinoidal, afterFinish: this._deinit.bind(this) } );
			else {
				$(this.MBwindow).hide();
				this._deinit();
			}
		} else throw("Modalbox is not initialized.");
	},
	
	_hide: function(event) { // Internal hide method to use with overlay and close link
		event.stop(); // Stop event propaganation for link elements
		/* Then clicked on overlay we'll check the option and in case of overlayClose == false we'll break hiding execution [Fix for #139] */
		if(event.element().id == 'MB_overlay' && !this.options.overlayClose) return false;
		this.hide();
	},
	
	alert: function(message){
		var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
		Modalbox.show(html, {title: 'Alert: ' + document.title, width: 300});
	},
		
	_appear: function() { // First appearing of MB
		if(Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) { // Preparing IE 6 for showing modalbox
			window.scrollTo(0,0);
			this._prepareIE("100%", "hidden"); 
		}
		this._setWidth();
		this._setPosition();
		if(this.options.transitions) {
			$(this.MBoverlay).setStyle({opacity: 0});
			new Effect.Fade(this.MBoverlay, {
					from: 0, 
					to: this.options.overlayOpacity, 
					duration: this.options.overlayDuration, 
					afterFinish: function() {
						new Effect.SlideDown(this.MBwindow, {
							duration: this.options.slideDownDuration, 
							transition: Effect.Transitions.sinoidal, 
							afterFinish: function(){ 
								this._setPosition(); 
								this.loadContent();
							}.bind(this)
						});
					}.bind(this)
			});
		} else {
			$(this.MBoverlay).setStyle({opacity: this.options.overlayOpacity});
			$(this.MBwindow).show();
			this._setPosition(); 
			this.loadContent();
		}
		this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
		Event.observe(window, "resize", this._setWidthAndPosition);
	},
	
	resize: function(byWidth, byHeight, options) { // Change size of MB without loading content
		var wHeight = $(this.MBwindow).getHeight();
		var wWidth = $(this.MBwindow).getWidth();
		var hHeight = $(this.MBheader).getHeight();
		var cHeight = $(this.MBcontent).getHeight();
		var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight - wHeight) : byHeight;
		if(options) this.setOptions(options); // Passing callbacks
		if(this.options.transitions) {
			new Effect.ScaleBy(this.MBwindow, byWidth, newHeight, {
					duration: this.options.resizeDuration, 
				  	afterFinish: function() { 
						this.event("_afterResize"); // Passing internal callback
						this.event("afterResize"); // Passing callback
					}.bind(this)
				});
		} else {
			this.MBwindow.setStyle({width: wWidth + byWidth + "px", height: wHeight + newHeight + "px"});
			setTimeout(function() {
				this.event("_afterResize"); // Passing internal callback
				this.event("afterResize"); // Passing callback
			}.bind(this), 1);
			
		}
		
	},
	
	resizeToContent: function(options){
		
		// Resizes the modalbox window to the actual content height.
		// This might be useful to resize modalbox after some content modifications which were changed ccontent height.
		
		var byHeight = this.options.height - this.MBwindow.offsetHeight;
		if(byHeight != 0) {
			if(options) this.setOptions(options); // Passing callbacks
			Modalbox.resize(0, byHeight);
		}
	},
	
	resizeToInclude: function(element, options){
		
		// Resizes the modalbox window to the camulative height of element. Calculations are using CSS properties for margins and border.
		// This method might be useful to resize modalbox before including or updating content.
		
		var el = $(element);
		var elHeight = el.getHeight() + parseInt(el.getStyle('margin-top')) + parseInt(el.getStyle('margin-bottom')) + parseInt(el.getStyle('border-top-width')) + parseInt(el.getStyle('border-bottom-width'));
		if(elHeight > 0) {
			if(options) this.setOptions(options); // Passing callbacks
			Modalbox.resize(0, elHeight);
		}
	},
	
	_update: function() { // Updating MB in case of wizards
		$(this.MBcontent).update("");
		this.MBcontent.appendChild(this.MBloading);
		$(this.MBloading).update(this.options.loadingString);
		this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];
		Modalbox.resize((this.options.width - this.currentDims[0]), (this.options.height - this.currentDims[1]), {_afterResize: this._loadAfterResize.bind(this) });
	},
	
	loadContent: function () {
		if(this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
			if(typeof this.content == 'string') {
				var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
				if(htmlRegExp.test(this.content)) { // Plain HTML given as a parameter
					this._insertContent(this.content.stripScripts());
					this._putContent(function(){
						this.content.extractScripts().map(function(script) { 
							return eval(script.replace("<!--", "").replace("// -->", ""));
						}.bind(window));
					}.bind(this));
				} else // URL given as a parameter. We'll request it via Ajax
					new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params, 
						onSuccess: function(transport) {
							var response = new String(transport.responseText);
							this._insertContent(transport.responseText.stripScripts());
							this._putContent(function(){
								response.extractScripts().map(function(script) { 
									return eval(script.replace("<!--", "").replace("// -->", ""));
								}.bind(window));
							});
						}.bind(this),
						onException: function(instance, exception){
							Modalbox.hide();
							throw('Modalbox Loading Error: ' + exception);
						}
					});
					
			} else if (typeof this.content == 'object') {// HTML Object is given
				this._insertContent(this.content);
				this._putContent();
			} else {
				Modalbox.hide();
				throw('Modalbox Parameters Error: Please specify correct URL or HTML element (plain HTML or object)');
			}
		}
	},
	
	_insertContent: function(content){
		$(this.MBcontent).hide().update("");
		if(typeof content == 'string') {
			setTimeout(function() { // Hack to disable content flickering in Firefox
				this.MBcontent.update(content);
			}.bind(this), 1);
		} else if (typeof content == 'object') { // HTML Object is given
			var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
			// If clonable element has ID attribute defined, modifying it to prevent duplicates
			if(content.id) content.id = "MB_" + content.id;
			/* Add prefix for IDs on all elements inside the DOM node */
			$(content).select('*[id]').each(function(el){ el.id = "MB_" + el.id; });
			this.MBcontent.appendChild(_htmlObj);
			this.MBcontent.down().show(); // Toggle visibility for hidden nodes
			if(Prototype.Browser.IE) // Toggling back visibility for hidden selects in IE
				$$("#MB_content select").invoke('setStyle', {'visibility': ''});
		}
	},
	
	_putContent: function(callback){
		// Prepare and resize modal box for content
		if(this.options.height == this._options.height) {
			setTimeout(function() { // MSIE sometimes doesn't display content correctly
				Modalbox.resize(0, $(this.MBcontent).getHeight() - $(this.MBwindow).getHeight() + $(this.MBheader).getHeight(), {
					afterResize: function(){
						this.MBcontent.show().makePositioned();
						this.focusableElements = this._findFocusableElements();
						this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
						setTimeout(function(){ // MSIE fix
							if(callback != undefined)
								callback(); // Executing internal JS from loaded content
							this.event("afterLoad"); // Passing callback
						}.bind(this),1);
					}.bind(this)
				});
			}.bind(this), 1);
		} else { // Height is defined. Creating a scrollable window
			this._setWidth();
			this.MBcontent.setStyle({overflow: 'auto', height: $(this.MBwindow).getHeight() - $(this.MBheader).getHeight() - 13 + 'px'});
			this.MBcontent.show();
			this.focusableElements = this._findFocusableElements();
			this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
			setTimeout(function(){ // MSIE fix
				if(callback != undefined)
					callback(); // Executing internal JS from loaded content
				this.event("afterLoad"); // Passing callback
			}.bind(this),1);
		}
	},
	
	activate: function(options){
		this.setOptions(options);
		this.active = true;
		$(this.MBclose).observe("click", this.hideObserver);
		if(this.options.overlayClose)
			$(this.MBoverlay).observe("click", this.hideObserver);
		$(this.MBclose).show();
		if(this.options.transitions && this.options.inactiveFade)
			new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
	},
	
	deactivate: function(options) {
		this.setOptions(options);
		this.active = false;
		$(this.MBclose).stopObserving("click", this.hideObserver);
		if(this.options.overlayClose)
			$(this.MBoverlay).stopObserving("click", this.hideObserver);
		$(this.MBclose).hide();
		if(this.options.transitions && this.options.inactiveFade)
			new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
	},
	
	_initObservers: function(){
		$(this.MBclose).observe("click", this.hideObserver);
		if(this.options.overlayClose)
			$(this.MBoverlay).observe("click", this.hideObserver);
		if(Prototype.Browser.IE)
			Event.observe(document, "keydown", this.kbdObserver);
		else
			Event.observe(document, "keypress", this.kbdObserver);
	},
	
	_removeObservers: function(){
		$(this.MBclose).stopObserving("click", this.hideObserver);
		if(this.options.overlayClose)
			$(this.MBoverlay).stopObserving("click", this.hideObserver);
		if(Prototype.Browser.IE)
			Event.stopObserving(document, "keydown", this.kbdObserver);
		else
			Event.stopObserving(document, "keypress", this.kbdObserver);
	},
	
	_loadAfterResize: function() {
		this._setWidth();
		this._setPosition();
		this.loadContent();
	},
	
	_setFocus: function() { 
		/* Setting focus to the first 'focusable' element which is one with tabindex = 1 or the first in the form loaded. */
		if(this.focusableElements.length > 0 && this.options.autoFocusing == true) {
			var firstEl = this.focusableElements.find(function (el){
				return el.tabIndex == 1;
			}) || this.focusableElements.first();
			this.currFocused = this.focusableElements.toArray().indexOf(firstEl);
			firstEl.focus(); // Focus on first focusable element except close button
		} else if($(this.MBclose).visible())
			$(this.MBclose).focus(); // If no focusable elements exist focus on close button
	},
	
	_findFocusableElements: function(){ // Collect form elements or links from MB content
		this.MBcontent.select('input:not([type~=hidden]), select, textarea, button, a[href]').invoke('addClassName', 'MB_focusable');
		return this.MBcontent.select('.MB_focusable');
	},
	
	_kbdHandler: function(event) {
		var node = event.element();
		switch(event.keyCode) {
			case Event.KEY_TAB:
				event.stop();
				
				/* Switching currFocused to the element which was focused by mouse instead of TAB-key. Fix for #134 */ 
				if(node != this.focusableElements[this.currFocused])
					this.currFocused = this.focusableElements.toArray().indexOf(node);
				
				if(!event.shiftKey) { //Focusing in direct order
					if(this.currFocused == this.focusableElements.length - 1) {
						this.focusableElements.first().focus();
						this.currFocused = 0;
					} else {
						this.currFocused++;
						this.focusableElements[this.currFocused].focus();
					}
				} else { // Shift key is pressed. Focusing in reverse order
					if(this.currFocused == 0) {
						this.focusableElements.last().focus();
						this.currFocused = this.focusableElements.length - 1;
					} else {
						this.currFocused--;
						this.focusableElements[this.currFocused].focus();
					}
				}
				break;			
			case Event.KEY_ESC:
				if(this.active) this._hide(event);
				break;
			case 32:
				this._preventScroll(event);
				break;
			case 0: // For Gecko browsers compatibility
				if(event.which == 32) this._preventScroll(event);
				break;
			case Event.KEY_UP:
			case Event.KEY_DOWN:
			case Event.KEY_PAGEDOWN:
			case Event.KEY_PAGEUP:
			case Event.KEY_HOME:
			case Event.KEY_END:
				// Safari operates in slightly different way. This realization is still buggy in Safari.
				if(Prototype.Browser.WebKit && !["textarea", "select"].include(node.tagName.toLowerCase()))
					event.stop();
				else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
					event.stop();
				break;
		}
	},
	
	_preventScroll: function(event) { // Disabling scrolling by "space" key
		if(!["input", "textarea", "select", "button"].include(event.element().tagName.toLowerCase())) 
			event.stop();
	},
	
	_deinit: function()
	{	
		this._removeObservers();
		Event.stopObserving(window, "resize", this._setWidthAndPosition );
		if(this.options.transitions) {
			Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
		} else {
			this.MBoverlay.hide();
			this._removeElements();
		}
		$(this.MBcontent).setStyle({overflow: '', height: ''});
	},
	
	_removeElements: function () {
		$(this.MBoverlay).remove();
		$(this.MBwindow).remove();
		if(Prototype.Browser.IE && !navigator.appVersion.match(/\b7.0\b/)) {
			this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
			window.scrollTo(this.initScrollX, this.initScrollY);
		}
		
		/* Replacing prefixes 'MB_' in IDs for the original content */
		if(typeof this.content == 'object') {
			if(this.content.id && this.content.id.match(/MB_/)) {
				this.content.id = this.content.id.replace(/MB_/, "");
			}
			this.content.select('*[id]').each(function(el){ el.id = el.id.replace(/MB_/, ""); });
		}
		/* Initialized will be set to false */
		this.initialized = false;
		this.event("afterHide"); // Passing afterHide callback
		this.setOptions(this._options); //Settings options object into intial state
	},
	
	_setWidth: function () { //Set size
		$(this.MBwindow).setStyle({width: this.options.width + "px", height: this.options.height + "px"});
	},
	
	_setPosition: function () {
		$(this.MBwindow).setStyle({left: Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2 ) + "px"});
		$(this.MBwindow).setStyle({top: (Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2 ) - 200) + "px"});
	},
	
	_setWidthAndPosition: function () {
		$(this.MBwindow).setStyle({width: this.options.width + "px"});
		this._setPosition();
	},
	
	_getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop)
			theTop = document.documentElement.scrollTop;
		else if (document.body)
			theTop = document.body.scrollTop;
		return theTop;
	},
	_prepareIE: function(height, overflow){
		$$('html, body').invoke('setStyle', {width: height, height: height, overflow: overflow}); // IE requires width and height set to 100% and overflow hidden
		$$("select").invoke('setStyle', {'visibility': overflow}); // Toggle visibility for all selects in the common document
	},
	event: function(eventName) {
		if(this.options[eventName]) {
			var returnValue = this.options[eventName](); // Executing callback
			this.options[eventName] = null; // Removing callback after execution
			if(returnValue != undefined) 
				return returnValue;
			else 
				return true;
		}
		return true;
	}
};

Object.extend(Modalbox, Modalbox.Methods);

if(Modalbox.overrideAlert) window.alert = Modalbox.alert;

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
  initialize: function(element, byWidth, byHeight, options) {
    this.element = $(element)
    var options = Object.extend({
	  scaleFromTop: true,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleByWidth: byWidth,
	  scaleByHeight: byHeight
    }, arguments[3] || {});
    this.start(options);
  },
  setup: function() {
    this.elementPositioning = this.element.getStyle('position');
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
	
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
	 if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
	  
	this.deltaY = this.options.scaleByHeight;
	this.deltaX = this.options.scaleByWidth;
  },
  update: function(position) {
    var currentHeight = this.dims[0] + (this.deltaY * position);
	var currentWidth = this.dims[1] + (this.deltaX * position);
	
	currentHeight = (currentHeight > 0) ? currentHeight : 0;
	currentWidth = (currentWidth > 0) ? currentWidth : 0;
	
    this.setDimensions(currentHeight, currentWidth);
  },

  setDimensions: function(height, width) {
    var d = {};
    d.width = width + 'px';
    d.height = height + 'px';
    
	//var topd  = Math.round((height - this.dims[0])/2);
	var leftd = Math.round((width  - this.dims[1])/2);
	if(this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
		if(!this.options.scaleFromTop) //d.top = this.originalTop-topd + 'px';
		d.left = this.originalLeft-leftd + 'px';
	} else {
		if(!this.options.scaleFromTop) //d.top = -topd + 'px';
		d.left = -leftd + 'px';
	}
	//SET A STATIC MARGIN FROM TOP TO ALLOW FOR LONGER LISTS - SUGGESTED TO HAVE THE DIALOG HAVE A OVERFLOW-Y TO ALLOW FOR MORE ROOM. 
	//DIGITAL MAELSTROM LLC 20090403 KSTICE
	d.top = "15px";
    this.element.setStyle(d);
  }
  

  
  
});