
var urlLoaded = window.location;

var regex = new RegExp('products\/(create|save)');
if( regex.test(urlLoaded) ) {

var buttonSaveClicked = false;	
	
function confirmClose()
  { 
  	if(!buttonSaveClicked) {
  	
    	return 'Сигурни ли сте, че искате да прекратите добавянето на продукт?';
  	}
  }
  window.onbeforeunload=confirmClose;   
  

  
}



function setLang(lng){
		var langs = [];
		langs['bg'] = 'bulgarian';
		langs['en'] = 'english';
		langs['ro'] = 'romanian';
		langs['ru'] = 'russian';
		langs['de'] = 'german';
		langs['sb'] = 'serbian';
		
		var languageString = 'sf_fieldset_';
		for(i in langs) {
		 if(typeof(langs[i]) == 'string') {
		 	if(typeof($(languageString+langs[i])) == 'object') {
				$(languageString+langs[i]).style.display = 'none';
				$('link_'+i).className = '';
			 
		 	}
		 }
		}
		$(languageString+langs[lng]).style.display = 'block';
		$('link_'+lng).className = 'selected';
	 
}

function setLangModal(lng){
		var langs = [];
		langs['bg'] = 'bulgarian';
		langs['en'] = 'english';
		langs['ro'] = 'romanian';
		langs['ru'] = 'russian';
		langs['de'] = 'german';
		langs['sb'] = 'serbian';
		
		var languageString = 'sf_fieldset_';
		for(i in langs) {
		 if(typeof(langs[i]) == 'string') {
		 	if(typeof($(languageString+langs[i]+'_modal')) == 'object') {
				$(languageString+langs[i]+'_modal').style.display = 'none';
				$('link_'+i+'_modal').className = '';
			 
		 	}
		 }
		}
		$(languageString+langs[lng]+'_modal').style.display = 'block';
		$('link_'+lng+'_modal').className = 'selected';
	 
}

function chooseSelectOption(selectId, searchValue) {
	var selectObject = $(selectId);
	
	var nodes = selectObject.childElements();
	for(var i = 0; i < nodes.length; i++) {		
		 if(nodes[i].text == searchValue) {
		   selectObject.selectedIndex = nodes[i].index;
		 }
	}
}


function beforePlaceBid(bid, bidValue, message, time, message2) {
	var bidObject = $(bid);
	bid = (bidObject.value);	
	bid = parseFloat(bid.replace(/^\$/, ''));
	if(time != '00:00')	{
		/*if(bid < bidValue)	{
			alert(message);
			return true;
		}*/ 
	} else {
		alert(message2);
	}
	return false;
}

function beforePlaceBid2(bid, currentBid, message, time, message2) {
	var bidObject = $(bid);
	currentBid = parseFloat($(currentBid).value);
	
  /*if(bidObject) {
	bid = (bidObject.value);
	bid = parseFloat(bid.replace(/^\$/, ''));
  }*/
	if(time != '00:00')	{
		/*if(bid <= currentBid)	{
			alert(message);
			return true;
		}*/ 
	} else {
		alert(message2);
	}
	return false;
}

function afterPlaceBid(currentBid, oldBid, minBid, currentHiddenBid, message) {
	
	var currentBidObject  = $(currentBid);
	var oldBidObject 	  = $(oldBid);
	var currentBidValue   = parseFloat(currentBidObject.value.replace(/^\$/, ''));
	currentHiddenBidOject =  $(currentHiddenBid);
	
	oldBidobject.value    = "$"+currentBidValue;
	
	currentBidValue       = currentBidValue + parseFloat(minBid);
	
	currentBidObject.value = "$"+currentBidValue;
	currentHiddenBidOject.value = currentBidValue;
	 
}


function placeAutobid(bid, message, messageEmpty) {
	var regex = /^[0-9]*\.?[0-9]+$/;	
	bid = $(bid).value;
	if(!bid) {
		alert(messageEmpty);
		return true;
	}
	if(!regex.test(bid)) {
		alert(message);
		return true;
	}
}

function toggleStreaming(container) {
	if(!getCookie('streaming')) {
		setCookie('streaming', 1);
		$(container).innerHTML = 'Streaming ON';
	} else {
		setCookie('streaming', "");
		$(container).innerHTML = 'Streaming OFF';
	}
	
	 
}

function setCookie (name,value,expires,path,domain,secure) {
  document.cookie = name + "=" + escape (value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
  }
  
  function getCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg) {
      return getCookieVal (j);
      }
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
    }
  return null;
  }
  
  function getCookieVal (offset) {
  var endstr = document.cookie.indexOf (";", offset);
  if (endstr == -1) { endstr = document.cookie.length; }
  return unescape(document.cookie.substring(offset, endstr));
  }
  
  function checkCashier() {
  	var checks = $$('input.checkbox');
  	var priceString = 0;
  	var priceCurrencyString = 0;
  	var currentPrice = 0;
  	var currentPriceCurrency = 0;
  	var currentPriceCurrencySign = '';
  	
  	for(i in checks) {
  	 if(typeof(checks[i]) !== 'function') {	
  		//checks[i].checked = !checks[i].checked;  
  		checks[i].checked = $('checkAll').checked;
  		eval('currentPrice = price_'+checks[i].value);
  		eval('currentPriceCurrency = price_currency_'+checks[i].value);
  		eval('currentPriceCurrencySign = price_currency_symbol_'+checks[i].value);
  		 
  		if(currentPrice !== null || currentPrice !== 0) {
  			currentPrice = parseFloat(currentPrice);
  			priceString += currentPrice;
  		}
  		
  		if(currentPriceCurrency !== null || currentPriceCurrency !== 0) {
  			currentPriceCurrency = parseFloat(currentPriceCurrency);
  			priceCurrencyString += currentPriceCurrency;
  		}
  		
  	 }
  	}
  	
  	if($('checkAll').checked && priceString)
  			$('totalCashier').update("$"+priceString + (priceCurrencyString ? " (" + currentPriceCurrencySign + priceCurrencyString + ")" : null));
  		else if(priceString) 
  			$('totalCashier').update('-');
  	
  }
  
  function checkCashierSingle() {
  	var checks = $$('input.checkbox');
  	var priceString = 0;
  	var priceCurrencyString = 0;
  	var currentPrice = 0;
  	var currentPriceCurrency = 0;
  	var currentPriceCurrencySign = '';
  		for(i in checks) {
  			if(typeof(checks[i]) !== 'function') {	
  				if(checks[i].checked) {
  					eval('currentPrice = price_'+checks[i].value);
			  		eval('currentPriceCurrency = price_currency_'+checks[i].value);
			  		eval('currentPriceCurrencySign = price_currency_symbol_'+checks[i].value);
			  		 
			  		if(currentPrice !== null || currentPrice !== 0) {
			  			currentPrice = parseFloat(currentPrice);
			  			priceString += currentPrice;
			  		}
			  		
			  		if(currentPriceCurrency !== null || currentPriceCurrency !== 0) {
			  			currentPriceCurrency = parseFloat(currentPriceCurrency);
			  			priceCurrencyString += currentPriceCurrency;
			  		}
  				}
  			}
  		}
  		if(priceString > 0) {
  			$total = '$'+priceString;
  			if (priceCurrencyString) {
  				$total += '('+currentPriceCurrency + priceCurrencyString + ')';
  			}
  			$('totalCashier').update($total);
  		}
  		else { 
  			$('totalCashier').update('-');
  		}
  }
  
  var globalHeading = '';
  function generateTitle2(title, checkboxObject, propertyValueId) {	 
  	
  		 
  		var checkboxes = $$('.checkboxTitle');
  		var flag = false;
  		var selector = '';
  		var updatePreview = '';
  		 tinyMCE.get('desc_en').setContent('');
	  	 tinyMCE.get('desc_bg').setContent('');
	  	 tinyMCE.get('desc_ro').setContent('');
	  	 tinyMCE.get('desc_ru').setContent('');
	  	 tinyMCE.get('desc_de').setContent('');
	  	 tinyMCE.get('desc_sb').setContent('');
	  	 
  		
  		eval('lang = lang_'+propertyValueId);
  		if(typeof(lang) !== 'undefined') {
  			for(i in lang) {
  				globalHeading = '';			  
				 if(typeof($('desc_'+i)) !== 'undefined') {	
				 	
				 	selector = 'desc_'+i;				 	
				 	eval("title = lang."+i); 
				 	var regx = new RegExp("(\s+?)?"+title, "i");
			  		for(i in checkboxes) {
			  			if(typeof(checkboxes[i]) !== 'function') {
			  				if(checkboxes[i].checked)
			  				flag = true;
			  			}
			  		}  		  		 
			  		if(flag){  			
			  		  if(checkboxObject.checked) {	 	
			  			globalHeading += title + ' ';
			  		  }
			  		  else {			  		  	
			  		  	globalHeading =	globalHeading.replace(regx, '');
			  		  }
			  		} else {
			  			globalHeading = '';			  			 
			  		}
			
					/*tinyMCE.get(selector).setContent('');*/
		  			tinyMCE.get(selector).setContent(globalHeading);
		  			if(i == 'bg') {
				 		updatePreview = globalHeading;
				 	}
				 }
  			}
  		}
  	 
  		$('titlePreview').update(updatePreview); 		  
  		
  } 
  
   
   
   function generateTitle(checkboxObject, propertyValueId,  container) {
   		var title = $(container).innerHTML;   		
   		//var langTitle = $message(propertyValueId, 'en');  
   		var langTitle = '';
   		var selectObject = $('property_'+propertyValueId);
   		if(selectObject) {
   		  langTitle = selectObject.options[selectObject.selectedIndex].text;
   		}
   		   		 
		if(langTitle) {
			var regx = new RegExp(langTitle, "i");   		
			
			if(checkboxObject.checked) {
				langTitle = title + ' '+langTitle;   			
				Messages.setOrder(selectObject.options[selectObject.selectedIndex].value);	  
			} else {
				langTitle = title.replace(regx, '');   	
				Messages.removeOrder(selectObject.options[selectObject.selectedIndex].value);		
			}   		
	
			$(container).update(langTitle); 	   		
		}

   }
   
   
   function updateLinkHandler() {
   		var langs = ['en', 'bg', 'ru', 'ro', 'sb', 'de'];  		
   	 
   		var order = Messages.getOrder();	    	 
  	 if(order.length > 0) {	 
   		for( i in langs ){
   		  if(typeof(langs[i]) !== 'function') {
	   		 var propertiesLang = '';
	   		 var selectorTiny = 'desc_'+langs[i];
	   			for( j in order ){
	   			 if(typeof(order[j]) !== 'function')
	   				propertiesLang += $message(order[j], langs[i]);
	   			}
	   			
	   			tinyMCE.get(selectorTiny).setContent(propertiesLang);
   			}
   		}
  	 }	 
   }
   
   function clearTitle() {
   		var checks = $$('.checkboxTitle');
   		for(i in checks) {
   			if(typeof(checks[i]) !== 'function') {
   				checks[i].checked = false;   				
   			}
   			Messages.clearOrder();
   			$("titlePreview").update('');
   		}
   }
   
   function appendGeneratedTitle() {
   		var json = '';
   		var order = Messages.getOrder();
   		if(order.length > 0) {
   			 json += order.join(',');
   		}		 
   		
   		if($('order')) {
   			$('sf_admin_edit_form').removeChild($('order'));
   		}
		var inputHidden = new Element('input', { type: 'hidden', value: json, name: 'order', id: 'order'});
   		$('sf_admin_edit_form').appendChild(inputHidden);
   }
   
   function parseNewValueXml(xml, propId) {   		 
   		var i = 0;
   		var xmlDoc = loadXMLString(xml);
   		var msgObj = 	  xmlDoc.getElementsByTagName('msg');
   		var optionTags =  xmlDoc.getElementsByTagName('option');
   		var selected = 	  xmlDoc.getElementsByTagName('selected');
   		var msg = '';
   		var options = ''; 
   		 
   		msg = msgObj[0].childNodes[0].nodeValue;   		 
   		if(optionTags.length > 0) {   	 
   		for(i = 0; i < optionTags.length; i++) {
   		  
   		var optionId = '';
   		var optionValue = '';	 
   			optionTags[i].normalize();   		 
   			 
   			for(var j = 0; j < optionTags[i].childNodes.length; j++) {
   			 if(optionTags[i].childNodes[j].firstChild !== null) {   			 	 
   			 	if(j == 1) {
   			 		optionId = optionTags[i].childNodes[j].firstChild.nodeValue;
   			 	} else if(j == 3) 
   			 		optionValue = optionTags[i].childNodes[j].firstChild.nodeValue;   			 	
   			 }
   				
   			}   			
   			$(propId).options[i] = new Option(optionValue, optionId);   			 
   		}
   		
	   		$(propId).selectedIndex = selected[0].firstChild.nodeValue;
	   		myModalbox.end(); 
	   		return false;
   		
   		}
   		
   		if(msg) alert(msg);
   		
   		
   }
   
      function parseNewValueXml2(xml, propId) {   		 
   		var i = 0;
   		var xmlDoc = loadXMLString(xml);
   		var msgObj = xmlDoc.getElementsByTagName('msg');
   		var optionTags =  xmlDoc.getElementsByTagName('option');
   		var msg = '';
   		var options = ''; 
   		
   		msg = msgObj[0].childNodes[0].nodeValue;   		 
   		/*if(optionTags.length > 0)   	 
   		for(i = 0; i < optionTags.length; i++) {
   		  
   		var optionId = '';
   		var optionValue = '';	 
   			optionTags[i].normalize();   		 
   			 
   			for(var j = 0; j < optionTags[i].childNodes.length; j++) {
   			 if(optionTags[i].childNodes[j].firstChild !== null) {   			 	 
   			 	if(j == 1) {
   			 		optionId = optionTags[i].childNodes[j].firstChild.nodeValue;
   			 	} else if(j == 3) 
   			 		optionValue = optionTags[i].childNodes[j].firstChild.nodeValue;   			 	
   			 }
   				
   			}   			
   			 			 
   		}*/
   		
   		 $("update").innerHMTL += optionTags;
   		
   		 
   }
   
   function loadXMLString(txt) 
{
	try //Internet Explorer
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(txt);
		return(xmlDoc); 
		}
		catch(e)
		{
		try //Firefox, Mozilla, Opera, etc.
		{
		parser=new DOMParser();
		xmlDoc=parser.parseFromString(txt,"text/xml");
		return(xmlDoc);
		}
		catch(e) {alert(e.message)}
		}
	return(null);
}

	function cartShipping(request, shipprice, totalprice, selectShippig) { 
		var selObj = $(selectShippig);
		var price = JSON.parse(request.responseText);
			 
		 if(price) {
				$(shipprice).update(price.shipprice);			
				$(totalprice).update(price.total);
			if(price.ship_id) {
				var nodes = selObj.childElements();
				for(var i = 0; i < nodes.length; i++) {		
					 if(parseInt(price.ship_id) ==  parseInt(nodes[i].value)) {
					   selObj.selectedIndex = nodes[i].index;
					 }
				}
			 
			}
		 }
		 
	}
	
	
	function togglePayment(type) {
		var containers = $$('.toggle_payment');
		for( i in containers ) {
			if(typeof(containers[i]) !== 'function') {
				containers[i].style.display = 'none';
			}
		}
 
		if($(type)) {
			$(type).style.display = 'block';
		}
	}
	
	
	function selectStatusList(el, url, listUrl, updateElement) {
		
    var editor=new Ajax.InPlaceEditor(el, url);
    Object.extend(editor, {
        createEditField: function() {
            var text=this.getText();

            var field=document.createElement("select");
            field.name="value";

            this.editField=field;
            this.form.appendChild(this.editField);

            new Ajax.Request(listUrl, {
                onSuccess: function(req) {
                     updateElement.update(req.responseText);
                }
                });
        }
    });
}

 function suncho (timeToSleep) {
 	timeToSleep *= 1000;
 	var sleeping = true;
 	var startedTime = new Date();
 	
 	while(sleeping) {
 		currentTime = new Date();
 		if(currentTime.getTime() - startedTime.getTime() >= timeToSleep) {
 			sleeping = false;
 		}
 	}
 }



	



/*Event.observe(document, 'dom:loaded', function () {
	var container = $('auctionsUpdate');
	
	if(typeof(container) == 'object' && container !== null) {
		var opt = {
			method: 'get',
			frequency: 3,
			onComplete: function() {
			 
			}
		};
		var url = 'http://localhost/bidz/web/frontend_dev.php/home/update';
		//var url = 'http://87.117.255.24/frontend.php/home/update';
		
		new Ajax.PeriodicalUpdater(
			container, url, opt
		);
		
	}
});*/
