IE = document.all?true:false;

var Tout;

function Toggle(id1,id2,obj,color){
  setTimeout(function(){ChangeColor(obj,color);},0);
  document.getElementById(id1).style.display ="none";
  document.getElementById(id2).style.display ="block";  
}

function ChangeColor(obj,color){
 obj.style.backgroundColor ="#"+color;
}


function linkMouseOver(obj){
 obj.style.backgroundColor ="#A33905";
 obj.style.color  = "#fff";
}


function linkMouseOut(obj){
 obj.style.backgroundColor="#fff";
 obj.style.color="#000";
}


function show(id,num){
 for(i=0;i<num;i++){
   if(document.getElementById('subm'+i)){
     document.getElementById('subm'+i).style.display="none";}
 }
 for(var i in document.getElementById('subm'))
   alert(i);
 if(Tout!="") clearTimeout(Tout); 
   document.getElementById('subm'+id+'').style.display="block";
}

function hide(id){
 if(Tout!="") clearTimeout(Tout); 
   Tout=setTimeout("document.getElementById('subm"+id+"').style.display='none'",500);
}




function lng(lng) {
	var current=window.location.href;
	var new_loc;
	if(/lng=/.test(current))
		new_loc=current.replace(/lng=\w*/,"lng="+lng);
	else if(/\?/.test(current))
		new_loc=current+"&lng="+lng;
	else 
		new_loc=current+"?lng="+lng;  
	window.location.replace(new_loc);
}

function default_currency(objSelect) {
	var new_loc;
	var current=window.location.href;
	var value = objSelect.options[objSelect.selectedIndex].value;
	
	if(/default_currency=/.test(current))
		new_loc=current.replace(/default_currency=\w*/,"default_currency="+value);
	else if(/\?/.test(current))
		new_loc=current+"&default_currency="+value;
	else 
		new_loc=current+"?default_currency="+value;  
	window.location.replace(new_loc);
}

/*
var send = function(link){
 var dataToSend =document.getElementById('calendar_y').value+"."+document.getElementById('calendar_m').value;
 var ajax = new httpAjaxRequest(); 
 if(ajax)
  {  
     ajax.prepareHash({date:dataToSend}); 
     ajax.open("GET", "ajax.php");
     ajax.send();
     ajax.getData();
     ajax.onreadystatechange = function()
       { 
           data =ajax.getResult();
           document.getElementById("calendar_div").innerHTML =data.calendar; 
       }  
  }
 else window.location =link + document.getElementById('calendar_y').value+"."+document.getElementById('calendar_m').value; 
}*/
var send = function(link){
	var dataToSend = document.getElementById('calendar_y').value+"."+document.getElementById('calendar_m').value;
	var ajax = new httpAjaxRequest(); 
	//var ajax_url = link.replace('index.php','ajax.php');
	var ajax_url = 'ajax.php' + link;
	if(ajax) {  
		ajax.prepareHash({date:dataToSend}); 
		ajax.open("GET", ajax_url);
		ajax.send();
		ajax.getData();
		ajax.onreadystatechange = function() { 
			data =ajax.getResult();
			document.getElementById("calendar_div").innerHTML =data.calendar; 
		}  
	}
	else window.location =link + document.getElementById('calendar_y').value+"."+document.getElementById('calendar_m').value; 
}

 
function showPic(pic,width,height) { 
  sDesrc = "width=" + width + ", height=" + height +
  		", status=no, toolbar=no, menubar=no, scrollbars=no";
  win=window.open("Gallery", "", sDesrc);
  win.document.write("<html><style>body{padding:0px;margin:0px;}</style><body>");
  win.document.write("<img src='uploads_script/gallery/"+pic+"' width='"+width+"' height='"+height+"'><br>");
  win.document.write("</body></html>");
  win.document.close();
} 

function showPic_(pic_src,width,height) { 
  sDesrc = "width=" + width + ", height=" + height + ", status=no, toolbar=no, menubar=no, scrollbars=no";
  win=window.open("Gallery", "", sDesrc);
  win.document.write("<html><style>body{padding:0px;margin:0px;}</style><body>");
  win.document.write("<img src='"+pic_src+"' width='"+width+"' height='"+height+"'><br>");
  win.document.write("</body></html>");
  win.document.close();
} 










function drawOptions(arr,selected){
  selected = selected||"";
  for(var i in arr){
     select = (i==selected)?"selected":'';
     document.write('<option value="'+i+'" '+select+'>'+arr[i]+'</option>');
   }
}

function switchCountry(obj,selected){
  selected = selected||'';
  var ind = obj.options[obj.selectedIndex].value; 
  var selbox2 = document.getElementById('city');
  delOptions(selbox2);
  for(var i in city){
    if(ind==city[i][0])
      createOption(selbox2,i,city[i][1],selected);
   } 
}

function createOption(parent,val,text,selected){
  var opt = document.createElement("option");
  opt.value = val;
  opt.innerHTML = text;
  if(val==selected)
	 opt.selected = true;
  parent.appendChild(opt);
}

function delOptions(obj){
  var count = obj.options.length-1; 
  for(i=count; i>0; i--)
	obj.removeChild(obj.options[i]);
}


function showVideo(name, width, height, autostart, showcontrols, showstatusbar, showdisplay, autorewind)//path,
{
	autostart = autostart ? autostart : 'True'; 
	showcontrols = showcontrols ? showcontrols : 'True';
	showstatusbar = showstatusbar ? showstatusbar : 'False';
	showdisplay = showdisplay ? showdisplay : 'False';						
	autorewind = autorewind ? autorewind : 'True';
	
	height = parseInt(height) + 50;
	
	var html = '';
	
    html += '<object width="' + width + '" height="' + height + '" classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95">\n';
    html += '<param name="Filename"      value="' + name + '">\n'; //+ path 
    html += '<param name="AutoStart"     value="' + autostart + '">\n';
    html += '<param name="ShowControls"  value="' + showcontrols + '">\n';
    html += '<param name="ShowStatusBar" value="' + showstatusbar + '">\n';
    html += '<param name="ShowDisplay"   value="' + showdisplay + '">\n';
    html += '<param name="AutoRewind"    value="' + autorewind + '">\n';

    html += '<embed type="application/x-mplayer2"\n'; 
    html += ' pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/"'; 
    html += ' width="'         + width + '"\n'; 
    html += ' height="'        + height + '"\n'; 
    html += ' src="'           + name + '"\n';//path + 
    html += ' filename="'      + name + '"\n';
    html += ' autostart="'     + autostart + '"\n';
    html += ' showcontrols="'  + showcontrols + '"\n';
    html += ' showstatusbar="' + showstatusbar + '"\n'; 
    html += ' showdisplay="'   + showdisplay + '"\n';
    html += ' autorewind="'    + autorewind + '">\n';
    html += '</embed>'; 
    html += '</object>\n';

	sDesrc = "width=" + width + ", height=" + height + ", status=no, toolbar=no, menubar=no, scrollbars=no";
	win = window.open("Video", "", sDesrc);
	win.document.write("<html>\n<style>\nbody{padding:0px;margin:0px;}</style>\n<body>\n");
	win.document.write(html);
	win.document.write("</body>\n</html>\n");
	win.document.close();
}


// ### COOKIE
/* v0.1
function writeCookie(cookieName, cookieContent, cookieExpireTime){
	var cookiePath = '/';
	if(cookieExpireTime>0){
		var expDate=new Date()
		expDate.setTime(expDate.getTime()+cookieExpireTime*1000*60*60)
		var expires=expDate.toGMTString()
		document.cookie=cookieName+"="+escape(cookieContent)+";path="+escape(cookiePath)+";expires="+expires+";";
	}
    else
		document.cookie=cookieName+"="+escape(cookieContent)+";path="+escape(cookiePath)+";";
}
*/
function baseDomainString(){
	e = document.domain.split(/\./);
	if(e.length > 1) {
		return(e[e.length-2] + "." +  e[e.length-1]);
	} else {
		return(document.domain);
	}
}

function writeCookie(cookieName, cookieContent, cookieExpireTime){
	var cookiePath = '/';
	if(cookieExpireTime>0){
		var expDate=new Date()
		expDate.setTime(expDate.getTime()+cookieExpireTime*1000*60*60)
		var expires=expDate.toGMTString()
		document.cookie=cookieName+"="+escape(cookieContent)+";path="+escape(cookiePath)+";expires="+expires+";domain="+baseDomainString();
		document.cookie=cookieName+"="+escape(cookieContent)+";path="+escape(cookiePath)+";expires="+expires+";domain=www."+baseDomainString();
	}
	else {
		document.cookie=cookieName+"="+escape(cookieContent)+";path="+escape(cookiePath)+";domain="+baseDomainString();
		document.cookie=cookieName+"="+escape(cookieContent)+";path="+escape(cookiePath)+";domain=www."+baseDomainString();
	}
}

function readCookie(cookieName){
	var ourCookie=document.cookie;
	if(!ourCookie || ourCookie=="")return "";
	ourCookie=ourCookie.split(";")
	var i=0;
	var Cookie;
	while(i<ourCookie.length){
		Cookie=ourCookie[i].split("=")[0];
		if(Cookie.charAt(0)==" ")
		Cookie=Cookie.substring(1);
		if(Cookie==cookieName){
			return unescape(ourCookie[i].split("=")[1]);
		}
		i++;
	}
	return "";
}

function deleteCookie(cookieName){
	var cookiePath = '/';
	document.cookie=cookieName+"="+readCookie(cookieName)+";path="+escape(cookiePath)+";expires=Thu, 01-Jan-1970 00:00:01 GMT;";
}


// GR
function previewPic(table_id,pic){
	//document.getElementById(table_id).style.backgroundImage = 'url('+pic+')';
	document.getElementById(table_id).innerHTML = '<img src="'+pic+'">';
	//document.getElementById(table_id).style.background = 'url('+pic+')';
	//document.getElementById(table_id).style.backgroundUrl = pic;
}

function CheckAll(formname,groupname) {
	for(i=0;i<document.forms[formname].elements.length;i++) {
		if(document.forms[formname].elements[i].name == groupname+"[]") {
			document.forms[formname].elements[i].checked = document.forms[formname].elements[i].checked?false:true;
		}
    }
}

function showHide(elmID,param) {
	var obj = document.getElementById(elmID);
	if (param == 'show' || param == 'block') {
		obj.style.display = 'block';
	}
	else if (param == 'hide' || param == 'none') {
		obj.style.display = 'none';
	}
	else {
		obj.style.display = (obj.style.display == 'none')?'block':'none';
	}
}

function CheckIsIE() {
	if (navigator.appName.toUpperCase() == 'MICROSOFT INTERNET EXPLORER') 
		return true;
	else
		return false;
}

// For printing iframes
function print_innerHTML(parseFrom,iframeTo,css_src) {
	document.getElementById(iframeTo).contentWindow.document.body.innerHTML = document.getElementById(parseFrom).innerHTML;
	if (CheckIsIE()==true) {
		iframe = eval ('document.'+iframeTo);
		iframe.close();
		//iframe.document.createStyleSheet(css_src);
		importCSS(get_DOC(document.getElementById(iframeTo)),css_src);
		iframe.focus();
		iframe.print();
	}
	else {
		//document.getElementById(iframeTo).close();
		
		importCSS(get_DOC(document.getElementById(iframeTo)),css_src);
		//document.iframeTo.createStyleSheet('./css/admin.css');
		//document.getElementById(iframeTo).document.createStyleSheet('./css/admin.css');
		document.getElementById(iframeTo).contentWindow.print();
	}
	//document.getElementById(iframeTo).print();
}

function importCSS(doc, css) {
	var css_ary = css.replace(/\s+/, '').split(',');
	var csslen, elm, headArr, x, css_file;

	for (x = 0, csslen = css_ary.length; x<csslen; x++) {
		css_file = css_ary[x];

		if (css_file != null && css_file != 'null' && css_file.length > 0) {
			// Is relative, make absolute
			if (css_file.indexOf('://') == -1 && css_file.charAt(0) != '/')
				css_file = this.documentBasePath + "/" + css_file;

			if (typeof(doc.createStyleSheet) == "undefined") {
				elm = doc.createElement("link");

				elm.rel = "stylesheet";
				elm.href = css_file;

				if ((headArr = doc.getElementsByTagName("head")) != null && headArr.length > 0)
					headArr[0].appendChild(elm);
			} else
				doc.createStyleSheet(css_file);
		}
	}
}

function get_DOC(iframe) {
	if(iframe.contentWindow) 
		return iframe.contentWindow.document;
	else if (iframe.contentDocument) 
		return iframe.contentDocument; 
	else 
		return iframe.document;
}


var suggest_products_founded = false;
function suggest(value,lang) {
	value = value.replace(/\s+/," ");
	div_id = 'suggest_products';
	if (value) {
		//window.status = value;
		var url = 'ajax_suggest_products.php?lng='+lang+'&search_products='+encodeURIComponent(value);
	    var myAjax = new Ajax.Updater	(div_id,url,{
	    														method: 'GET',
	    														evalScripts: true,
	    														//onComplete:   function() { showHide(div_id,'show'); },
	    														onException:  function() { document.forms['SF_products_search'].submit(); }
	    													}
	    								);
	}
	else {
		showHide(div_id,'hide');
		window.status = 'no value';
	}
}

function getHoursPrice(div_id,value_lang) {
	value_city	= document.getElementById('city').value;
	value_hours	= document.getElementById('hours').value;
	var url = 'ajax_hours_prices.php?lng='+value_lang+'&city='+value_city+'&hours='+value_hours;
    var myAjax = new Ajax.Updater	(div_id,url,{method: 'GET', evalScripts: true } );
	//alert(value_lang);
}

function show_popupMap(dist_id) {
	sDesrc = "width=600, height=300, status=no, toolbar=no, menubar=no, scrollbars=yes, resizable=yes";
	win = window.open("/index_distribution_map.php?dist_id="+dist_id, "Distribution_map", sDesrc);
	win.document.close();
	win.focus();
}

function show_popupStructure(dist_id) {
	sDesrc = "width=600, height=500, status=no, toolbar=no, menubar=no, scrollbars=yes, resizable=yes";
	win = window.open("/index_structure.php?dist_id="+dist_id, "Map", sDesrc);
	win.document.close();
	win.focus();
}


function products_comparison(div_id,url,self_call) {
	var myAjax = new Ajax.Updater	(div_id,url,{
													method: 'GET',
													evalScripts: true,
													//onComplete:   function() { showHide(div_id,'show'); },
													onComplete:   function() { if (self_call) products_comparison(div_id,url); },
													onException:  function() { top.location.href = url; }
												}
							);
}













function this_X(elemID) {
	var obj = document.getElementById(elemID);
	var x=0; 
	var elm = obj.parentNode.offsetParent;
	while(elm) {
		x  += elm.offsetLeft;
		elm = elm.offsetParent;
	}
	return x;
}

function this_Y(elemID) {
	var obj = document.getElementById(elemID);
	var y=0; 
	var elm = obj.parentNode.offsetParent;
	while(elm) {
		y += elm.offsetTop;
		elm = elm.offsetParent;
	}
	return y;
}




function StringCompare(aComp, bComp) {
  if (aComp.toLowerCase() < bComp.toLowerCase()) return -1;
  if (aComp.toLowerCase() > bComp.toLowerCase()) return  1;
  return 0;
}

function Inspect(Instance) {
  var x = 10;
  var y = 10;
  var width  = 640;
  var height = 480;
  if ((parseInt(navigator.appVersion) >= 4) || navigator.product == 'Gecko')
    {
    x = (screen.width  - width ) / 2;
    y = (screen.height - height) / 2;
    }

  var hwnd = window.open('', 'inspect', 'top=' + y + ',left=' + x + ',width=' + width + ',height='+ height + ',resizable=yes,scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no');

  properties = new Array();
  propindex  = 0;
  for (property in Instance) properties[propindex++] = property;
  properties.sort(StringCompare);
  for (i = 0; i < properties.length; i++)
    hwnd.document.write('.<span style="font: 8pt monospace;"><span style="color: Red;">' + properties[i] + '</span> = <span style="color: green;">' + Instance[properties[i]] + '</span></span><br>');
}


function mktime() {
    var d = new Date(), r = arguments, i = 0,
        e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];
 
    for (i = 0; i < e.length; i++) {        if (typeof r[i] === 'undefined') {
            r[i] = d['get' + e[i]]();
            r[i] += (i === 3); // +1 to fix JS months.
        } else {
            r[i] = parseInt(r[i], 10);            if (isNaN(r[i])) {
                return false;
            }
        }
    }    
    // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000.
    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);
    
    // Set year, month (-1 to fix JS months), and date.    // !This must come before the call to setHours!
    d.setFullYear(r[5], r[3] - 1, r[4]);
    
    // Set hours, minutes, and seconds.
    d.setHours(r[0], r[1], r[2]); 
    // Divide milliseconds by 1000 to return seconds and drop decimal.
    // Add 1 second if negative or it'll be off from PHP by 1 second.
    return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
}

function ajax_subscribe(div_parseInto,url,elId_email) {
	url = url + '&email=' + document.getElementById(elId_email).value;
	$.get(
		url,
		function(data) {
			$("#"+div_parseInto+"").html(data);
		}
	);
}

function displayKeyCode(evt) {
	var charCode = (evt.which) ? evt.which : event.keyCode;
	
	return charCode;
}

function StrechVerticalHeights(el1, el2) {
    var container  = document.getElementById(el1);
    var container2 = document.getElementById(el2);
    //alert(container2.clientHeight);
    if(container.clientHeight > container2.clientHeight){
        container2.style.height = container.clientHeight+'px';
    }else{
        container.style.height = container2.clientHeight+'px';
    }
    
    return true;
}

function StrechVerticalHeights_(element_array) {
	var max_height = 0;
	for (i=0; i<element_array.length; i++) {
		max_height = Math.max(document.getElementById(element_array[i]).clientHeight, max_height);
	}
	
	for (i=0; i<element_array.length; i++) {
		document.getElementById(element_array[i]).style.height = max_height+'px';
	}
}

function StrechVerticalHeights_by_jquery(attribName) {
	var max_height = 0;
	var n = $(attribName).length;
	
	var heights_array = new Array();
	
	if (n>1) {
		for (i=0; i<n; i++) {
			//max_height = Math.max($(attribName).eq(i).height(), max_height);
			heights_array[i] = $(attribName[i]).height();
			max_height = Math.max($(attribName[i]).height(), max_height);
		}
		
		if (max_height) {
			for (i=0; i<n; i++) {
				if (heights_array[i] < max_height) {
					$(attribName[i]).height(max_height + 'px');
				}
			}
		}
		
		return true;
	}
	
	return false;
}

function StrechVerticalHeights_by_jquery_AttribName(attribName) {
	var max_height = 0;
	var n = $(attribName).length;
	
	var heights_array = new Array();
	
	if (n>1) {
		for (i=0; i<n; i++) {
			max_height = Math.max($(attribName).eq(i).height(), max_height);
		}
		
		if (max_height) {
			$(attribName).height(max_height + 'px');
		}
		
		return true;
	}
	
	return false;
}

















// 10:49 PM 2010-11-08
function AjaxSubmit_form(formname, url, div_parseInto, httpmethod) {
	/*
	var httpmethod = (httpmethod=='POST')?'POST':'GET';
    var Param = Form.serialize(formname);
    var myAjax = new Ajax.Updater (div_parseInto,url,{method: httpmethod, parameters: Param, evalScripts: true, onComplete: showResult});
    //alert(myAjax.Responders);
    */
    
    httpmethod = (httpmethod == 'GET') ? 'GET' : 'POST';
    
    var jqxhr = $.ajax({
    	'type': 'POST',
		'url': url,
    	data: $("#"+formname).serialize(),
    	success: function(data) {$("#"+div_parseInto+"").html(data);}
    });
    
    return jqxhr;
}

function AjaxSubmit_noform(url, div_parseInto) {
	//var myAjax = new Ajax.Updater (div_parseInto,url,{method: "GET", evalScripts: true, onComplete: showResult}); //alert(myAjax.Responders);
	
	var jqxhr = $.get(
		url,
		function(data) {
			$("#"+div_parseInto+"").html(data);
		}
	);
	//jqxhr.complete(function() { alert("second complete"); })
    
    return jqxhr;
}
