// $Id: common.js,v 1.12.2.24 2008/04/18 12:24:52 max Exp $

//
// Enviroment identificator
//
var localIsDOM = document.getElementById?true:false;
var localIsJava = navigator.javaEnabled();
var localIsStrict = document.compatMode=='CSS1Compat';
var localPlatform = navigator.platform;
var localVersion = "0";
var localBrowser = "";
var localBFamily = "";
var isHttps = false;
if (window.opera && localIsDOM) {
	localBFamily = localBrowser = "Opera";
	if (navigator.userAgent.search(/^.*Opera.([\d.]+).*$/) != -1)
		localVersion = navigator.userAgent.replace(/^.*Opera.([\d.]+).*$/, "$1");
	else if (window.print)
		localVersion = "6";
	else
		localVersion = "5";
} else if (document.all && document.all.item)
	localBFamily = localBrowser = 'MSIE';
if (navigator.appName=="Netscape") {
	localBFamily = "NC";
	if (!localIsDOM) {
		localBrowser = 'Netscape';
		localVersion = navigator.userAgent.replace(/^.*Mozilla.([\d.]+).*$/, "$1");
		if(localVersion != '')
			localVersion = "4";
	} else if(navigator.userAgent.indexOf("Safari") >= 0)
		localBrowser = 'Safari';
	else if (navigator.userAgent.indexOf("Netscape") >= 0)
		localBrowser = 'Netscape';
	else if (navigator.userAgent.indexOf("Firefox") >= 0)
		localBrowser = 'Firefox';
	else 
		localBrowser = 'Mozilla';
	
}
if (navigator.userAgent.indexOf("MSMSGS") >= 0)
	localBrowser = "WMessenger";
else if (navigator.userAgent.indexOf("e2dk") >= 0)
	localBrowser = "Edonkey";
else if (navigator.userAgent.indexOf("Gnutella") + navigator.userAgent.indexOf("Gnucleus") >= 0)
	localBrowser = "Gnutella";
else if (navigator.userAgent.indexOf("KazaaClient") >= 0)
	localBrowser = "Kazaa";

if (localVersion == '0' && localBrowser != '') {
	var rg = new RegExp("^.*"+localBrowser+".([\\d.]+).*$");
	localVersion = navigator.userAgent.replace(rg, "$1");
}
var localIsCookie = ((localBrowser == 'Netscape' && localVersion == '4')?(document.cookie != ''):navigator.cookieEnabled);

if (document.location.protocol == "https:") { 
    isHttps = true;
}

function change_antibot_image(id) {
	var image = document.getElementById(id);
	if (image)
		image.src = xcart_web_dir+"/antibot_image.php?tmp="+Math.random()+"&section="+id+"&regenerate=Y";
}


/*
	Find element by classname
*/
function getElementsByClassName( clsName ) {
	var arr = new Array(); 
	var elems = document.getElementsByTagName("*");
	
	for ( var cls, i = 0; ( elem = elems[i] ); i++ ) {
		if ( elem.className == clsName ) {
			arr[arr.length] = elem;
		}
	}
	return arr;
}
//
// Opener/Closer HTML block
//
function visibleBox(id,skipOpenClose) {
	elm1 = document.getElementById("open"+id);
	elm2 = document.getElementById("close"+id);
	elm3 = document.getElementById("box"+id);

	if(!elm3)
		return false;

	if (skipOpenClose) {
		elm3.style.display = (elm3.style.display == "")?"none":"";
	} else if(elm1) {
		if (elm1.style.display == "") {
			elm1.style.display = "none";
			if(elm2)
				elm2.style.display = "";
			elm3.style.display = "none";
			var class_objs = getElementsByClassName('DialogBox');
			for (var i = 0; i < class_objs.length; i++) {
				class_objs[i].style.height = "1%";
			}
		} else {
			elm1.style.display = "";
			if(elm2)
				elm2.style.display = "none";
			elm3.style.display = "";
		}
	}
}

/*
	URL encode
*/
function urlEncode(url) {
	return url.replace(/\s/g, "+").replace(/&/, "&amp;").replace(/"/, "&quot;")
}

/*
	Math.round() wrapper
*/
function round(n, p) {
	if (isNaN(n))
		n = parseFloat(n);
	if (!p || isNaN(p))
		return Math.round(n);
	p = Math.pow(10, p);
	return Math.round(n*p)/p;
}

/*
	Price format
*/
function price_format(price, thousand_delim, decimal_delim, precision) {
	var thousand_delim = (arguments.length > 1 && thousand_delim !== false) ? thousand_delim : number_format_th;
	var decimal_delim = (arguments.length > 2 && decimal_delim !== false) ? decimal_delim : number_format_dec;
	var precision = (arguments.length > 3 && precision !== false) ? precision : number_format_point;

	if (precision > 0) {
		precision = Math.pow(10, precision);
		price = Math.round(price*precision)/precision;
		var top = Math.floor(price);
		var bottom = Math.round((price-top)*precision)+precision;

	} else {
		var top = Math.round(price);
		var bottom = 0;
	}

	top = top+"";
	bottom = bottom+"";
	var cnt = 0;
	for (var x = top.length; x >= 0; x--) {
		if (cnt % 3 == 0 && cnt > 0 && x > 0)
			top = top.substr(0, x)+thousand_delim+top.substr(x, top.length);

		cnt++;
	}

	return (bottom > 0) ? (top+decimal_delim+bottom.substr(1, bottom.length)) : top;
}

/*
	Substitute
*/
function substitute(lbl) {
var x, rg;
	for(x = 1; x < arguments.length; x+=2) {
		if(arguments[x] && arguments[x+1]) {
			rg = new RegExp("\\{\\{"+arguments[x]+"\\}\\}", "gi");
			lbl = lbl.replace(rg,  arguments[x+1]);
			rg = new RegExp('~~'+arguments[x]+'~~', "gi");
			lbl = lbl.replace(rg,  arguments[x+1]);
		}
	}
	return lbl;
}

function getWindowOutWidth(w) {
	if (!w)
		w = window;
	if (localBFamily == "MSIE")
		return w.document.body.clientWidth;
	else
		return w.outerWidth;
}

function getWindowOutHeight(w) {
	if (!w)
		w = window;
	if (localBFamily == "MSIE")
		return w.document.body.clientHeight;
	else
		return w.outerHeight;
}

function getWindowWidth(w) {
	if (!w)
		w = window;
    if (localBFamily == "MSIE")
		return w.document.body.clientWidth;
    else 
		return w.innerWidth;
}

function getWindowHeight(w) {
	if (!w)
		w = window;
    if (localBFamily == "MSIE")
		return w.document.body.clientHeight;
	else
		return w.innerHeight;
}

function getDocumentHeight(w){
	if (!w)
		 w = window;
	if (localBFamily == "MSIE" || (localBFamily == "Opera" && localVersion >= 7 && localVersion < 8))
		return isStrict ? w.document.documentElement.scrollHeight : w.document.body.scrollHeight;
	if (localBFamily == "NC")
		return w.document.height
	if (localBFamily == "Opera")
		return w.document.body.style.pixelHeight
}

function getDocumentWidth(w) {
	if (!w)
		w = window;
	if (localBFamily == "MSIE" || (localBFamily == "Opera" && localVersion >= 7 && localVersion < 8))
		return isStrict ? w.document.documentElement.scrollWidth : w.document.body.scrollWidth;
	if (localBFamily == "NC")
		return w.document.width;
	if (localBFamily == "Opera")
		return w.document.body.style.pixelWidth;
}

function expandWindowX(w, step, limit) {
	if (!w)
		w = window;

	if (!step)
		step = 10;

	var go = true;
	var i = 200;
	while (go && i--) {
		if (limit && getWindowOutWidth()+step > limit)
			break;

		try {
			w.scrollTo(step, 0);
			go = (w.document.documentElement && w.document.documentElement.scrollLeft > 0) || (w.document.body && w.document.body.scrollLeft > 0);
			if (go)
				w.resizeBy(step, 0);

		} catch (e) {
			return false;
		}
	}

	return true;
}

function expandWindowY(w, step, limit) {
	if (!w)
		w = window;

	if (!step)
		step = 10;

	var go = true;
	var i = 200;
	while (go && i--) {
		if (limit && getWindowOutHeight()+step > limit)
			 break;

		try {
			w.scrollTo(0, step);
			go = (w.document.documentElement && w.document.documentElement.scrollTop > 0) || (w.document.body && w.document.body.scrollTop > 0);
			if (go)
				w.resizeBy(0, step);

		} catch(e) {
			return false;
		}
	}

	return true;
}

/*
	Check list of checkboxes
*/
function checkMarks(form, reg, lbl) {
var is_exist = false;

	if (form.elements.length == 0)
		return true;

	for (var x = 0; x < form.elements.length; x++) {
		if (form.elements[x].name.search(reg) == 0 && form.elements[x].type == 'checkbox' && !form.elements[x].disabled) {
			is_exist = true;
			if (form.elements[x].checked)
				return true;
		}
	}

	if (!is_exist)
		return true;
	else if (lbl)
		alert(lbl);
	else if (lbl_no_items_have_been_selected)
		alert(lbl_no_items_have_been_selected);
	return false;
}

/*
	Submit form with specified value of 'mode' parmaeters
*/
function submitForm(formObj, formMode) {
	if (!formObj)
		return false;
	if (formObj.tagName != "FORM") {
		if (!formObj.form)
			return false;
		formObj = formObj.form;
	}
	if (formObj.mode)
		formObj.mode.value = formMode;
	formObj.submit();
}

/*
	Analogue of PHP function sleep()
*/
function sleep(msec) {
	var then = new Date().getTime()+msec;
	while (then >= new Date().getTime()){
	}
}

/*
	Convert number from current format
	(according to 'Input and display format for floating comma numbers' option)
	to float number
*/
function convert_number(num) {
	var regDec = new RegExp(reg_quote(number_format_dec), "gi");
	var regTh = new RegExp(reg_quote(number_format_th), "gi");
	var pow = Math.pow(10, parseInt(number_format_point));
	num = parseFloat(num.replace(" ", "").replace(regTh, "").replace(regDec, "."));
	return Math.round(num*pow)/pow;
}

/*
	Check string as number
	(according to 'Input and display format for floating comma numbers' option)
*/
function check_is_number(num) {
	var regDec = new RegExp(reg_quote(number_format_dec), "gi");
	var regTh = new RegExp(reg_quote(number_format_th), "gi");
	num = num.replace(" ", "").replace(regTh, "").replace(regDec, ".");
	return (num.search(/^[+-]?[0-9]+(\.[0-9]+)?$/) != -1);
}

/*
	Qutation for RegExp class
*/
function reg_quote(s) {
	return s.replace(/\./g, "\\.").replace(/\//g, "\\/").replace(/\*/g, "\\*").replace(/\+/g, "\\+").replace(/\[/g, "\\[").replace(/\]/g, "\\]");
}

function setCookie(name, value, path, expires) {
	if (typeof(expires) == 'object') {
		try {
			var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
			var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
			if (days[expires.getDay()] && months[expires.getMonth()])
				expires = days[expires.getDay()]+" "+expires.getDate()+"-"+months[expires.getMonth()]+"-"+expires.getFullYear()+" "+expires.getHours()+":"+expires.getMinutes()+":"+expires.getSeconds()+" GMT";
		} catch(e) { }
	}

	if (typeof(expires) != 'string')
		expires = false;

	document.cookie = name+"="+escape(value)+(expires ? "; expires=" + expires : "")+(path ? "; path="+path : "");
}

function deleteCookie(name) {
	document.cookie = name+"=0; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
}

/*
	Clone object
*/
function cloneObject(orig) {
	var r = {};
	for (var i in orig) {
		r[i] = orig[i];
	}

	return r;
}

/*
	Get first checkbox and redirect to URL
*/
function getFirstCB(form, reg) {

	while (form.tagName && form.tagName.toUpperCase() != 'FORM')
		form = form.parentNode;

	if (!form.tagName || form.tagName.toUpperCase() != 'FORM' || form.elements.length == 0)
        return false;

	var selectedChk = false;
    for (var x = 0; x < form.elements.length; x++) {
        if (form.elements[x].name.search(reg) == 0 && form.elements[x].type == 'checkbox' && !form.elements[x].disabled && form.elements[x].checked) {
			selectedChk = form.elements[x];
			break;
        }
    }
    
    if (!selectedChk) {
		if (lbl_no_items_have_been_selected)
			alert(lbl_no_items_have_been_selected);

        return false;
	}

    return selectedChk;
}

/*
	getElementById() wrapper
*/
function _getById(id) {
	if (typeof(id) != 'string' || !id)
		return false;

	var obj = document.getElementById(id);
	if (obj && obj.id != id) {
		obj = false;
		for (var i = 0; i < document.all.length && obj === false; i++) {
			if (document.all[i].id == id)
				obj = document.all[i];
		}
	}

	return obj;
}

// undefined or not
function isset(obj) {
	return typeof(obj) != 'undefined' && obj !== null;
}


// Check - variable is function or not
function isFunction(f) {
	return (typeof(f) == 'function' || (typeof(f) == 'object' && (f+"").search(/\s*function /) === 0));
}


function chProdImage(src, id, det){
	var img = document.getElementById(id);
	var aTag = document.getElementById('a_product_thumbnail');
	if(img)
		img.src = src;
	if(aTag)
		aTag.href = det;
}

function globalLeft(eElement)
{
   if (!eElement && this)                    // if argument is invalid
   {                                         // (not specified, is null or is 0)
      eElement = this;                       // and function is a method
   }                                         // identify the element as the method owner

   var DL_bIE = document.all ? true : false; // initialize var to identify IE

   var nLeftPos = eElement.offsetLeft;       // initialize var to store calculations
   var eParElement = eElement.offsetParent;  // identify first offset parent element

   while (eParElement != null)
   {                                         // move up through element hierarchy

      if(DL_bIE)                             // if browser is IE, then...
      {
         if( (eParElement.tagName != "TABLE") && (eParElement.tagName != "BODY") )
         {                                   // if parent is not a table or the body, then...
            nLeftPos += eParElement.clientLeft; // append cell border width to calcs
         }
      }
      else                                   // if browser is Gecko, then...
      {
         if(eParElement.tagName == "TABLE")  // if parent is a table, then...
         {                                   // get its border as a number
            var nParBorder = parseInt(eParElement.border);
            if(isNaN(nParBorder))            // if no valid border attribute, then...
            {                                // check the table's frame attribute
               var nParFrame = eParElement.getAttribute('frame');
               if(nParFrame != null)         // if frame has ANY value, then...
               {
                  nLeftPos += 1;             // append one pixel to counter
               }
            }
            else if(nParBorder > 0)          // if a border width is specified, then...
            {
               nLeftPos += nParBorder;       // append the border width to counter
            }
         }
      }
      nLeftPos += eParElement.offsetLeft;    // append left offset of parent
      eParElement = eParElement.offsetParent; // and move up the element hierarchy
   }                                         // until no more offset parents exist
   return nLeftPos;                          // return the number calculated
}

function showlayer(layer,obj){
    var myLayer=document.getElementById(layer);
    left = globalLeft(obj);
    if(myLayer.style.display=="none" || myLayer.style.display==""){
        myLayer.style.display="block";
	 myLayer.style.left = (left-270)+'px';
    } else { 
        myLayer.style.display="none";
        }
}

var param = '';
var pref='';
if(cur_page == 'catalog')
	pref= 'home.php?cat='+cur_cat;
if(cur_page == 'search')
	pref= 'search.php?mode=search';
if(cur_page == 'manufacturer_products')
	pref= 'manufacturers.php?manufacturerid='+cur_manuf;

function refresh(obj){
    url = obj.href;
    param = URLDecode(parent.location.hash.substr(1));
    var ind = url.indexOf('?');
    addparam = url.substr(ind+1);
    addparam=addparam.replace(/\s/g,"%20");
    re = '%5B0%5D';
    addparam=addparam.replace(re,"[]");
	if(cur_page == 'search'){
		re ='mode=search';	
		addparam=addparam.substr(12);
	}

    addparam2 = URLDecode(addparam);
    param = param.replace(/\s/g,"%20");
    var exist	= param.indexOf(addparam2);
 
    if(exist > 0){
	obj.className = '';
	re = '&'+addparam2;
	param = param.replace(re,'');
    }else{
	obj.className = 'act';
	param = param +'&'+ addparam2;
    }
	if(param.length)
		parent.location.hash = param;
	else
		parent.location.hash = ' ';
    new Ajax.Updater('contentcolumn', pref+param, { method: 'get', parameters:{ajax:1}});
    new Ajax.Updater('leftcolumn', pref+param, { method: 'get', parameters:{ajax:2}});
	

	return false;
}

function pagenom(nom){
	if(!cur_cat && cur_page != 'search' && cur_page !='manufacturer_products') return true;

       param = parent.location.hash.substr(1);
	re = /&page=\d*/;
	param = param.replace(re,'');

	re = /^page=\d*/;
	param = param.replace(re,'');
	if(param.length)
		parent.location.hash = param+'&page='+nom;
	else
		parent.location.hash = param+'page='+nom;
       new Ajax.Updater('contentcolumn', pref+param+'&page='+nom, { method: 'get', parameters:{ajax:1}});
	return false;
}

function sort_by(l){
	if(!cur_cat && cur_page != 'search' && cur_page !='manufacturer_products') return true;

       param = parent.location.hash.substr(1);

	re = /&sort=[a-z]*/;
	param = param.replace(re,'');

	re = /^sort=[a-z]*/;
	param = param.replace(re,'');

	re = /&sort_direction=\d/;
	param = param.replace(re,'');

	re = /sort_direction=\d/;
	param = param.replace(re,'');

	if(param.length)
		parent.location.hash = param+'&'+l;
	else
		parent.location.hash = param+l;
       new Ajax.Updater('contentcolumn', pref+'&'+parent.location.hash.substr(1), { method: 'get', parameters:{ajax:1}});
	return false;

}


function objects_per_page(listValue){
	if(!cur_cat && cur_page != 'search' && cur_page !='manufacturer_products') return true;

       param = parent.location.hash.substr(1);
	re = /&objects_per_page=\d*/;
	param = param.replace(re,'');

	re = /objects_per_page=\d*/;
	param = param.replace(re,'');


	if(param.length)
		parent.location.hash = param+'&objects_per_page='+listValue;
	else
		parent.location.hash = param+'objects_per_page='+listValue;
       new Ajax.Updater('contentcolumn', pref+param+'&objects_per_page='+listValue, { method: 'get', parameters:{ajax:1}});
	return false;
}

function clear_sel(){
	parent.location.hash = ' ';
	elems = $$('a.act');
	for (var i=0;i<elems.length;i++){
		elems[i].className = '';
	}	
       new Ajax.Updater('contentcolumn', pref, { method: 'get', parameters:{ajax:1}});
    	new Ajax.Updater('leftcolumn', pref, { method: 'get', parameters:{ajax:2}});

	return false;
}

function set_act_class(){
	param = URLDecode(parent.location.hash.substr(1));
	elems = $$('#leftcolumn a');
	var exist = 0;
	for (var i=0;i<elems.length;i++){
		url = elems[i].href;
		ind = url.indexOf('?');
    		addparam = url.substr(ind+1);
		addparam=addparam.replace(/\s/g,"%20");
		re = '%5B0%5D';
		addparam=addparam.replace(re,"[]");

    		addparam2 = URLDecode(addparam);
		
		param = param.replace(/\s/g,"%20");
    		exist = param.indexOf(addparam2);

    		if(exist > 0){
			elems[i].className = 'act';
		}else{

			if(document.URL.indexOf(addparam)> 0)
				elems[i].className = 'act';
		}
	}
}

function read_hesh(){
	var dloc = (document.location.href);
	re = '%5B0%5D';
       dloc=URLDecode(dloc.replace(re,"[]"));
	extra = dloc.indexOf('furniture');
	productid = dloc.indexOf('productid');
	search = dloc.indexOf('search.php');
	cart = dloc.indexOf('cart.php');
 
	if(productid > 0 || search > 0 || cart > 0)
		return false;
	
	ind = dloc.indexOf('?');
	
	if(extra <=0)
		return false;
	if(dloc.indexOf('cat') > 0 && dloc.indexOf('&')<=0)
		ind = 0
	param = '';
	if(ind > 0 && parent.location.hash ==''){
		addparam = '&'+dloc.substr(ind+1);
		parent.location.hash = parent.location.hash+addparam;
	}
	else
		addparam = '';

	if(parent.location.hash.length > 5){
		param = parent.location.hash.substr(1);
		if(param.length >5){
		       new Ajax.Updater('contentcolumn', pref+param, { method: 'get', parameters:{ajax:1}});
	    		new Ajax.Updater('leftcolumn', pref, { method: 'get', parameters:{ajax:2}});

		}
		set_act_class();
	}
	return false;
}

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}
