/**
 *  PHPMass Shopping Cart
 * Copyright (C) 2008  PHPMass.com
 * 
 *  This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

 
function toggleVisibility(id){
	var e = document.getElementById(id);
	if(e.style.display != 'none')
	e.style.display = 'none';
	else
	e.style.display = 'block';
}

function filterProdsByMan(SelectLocation,ManID){
	var ProdSelect = $('prodswitch'+SelectLocation);
	var OptArr = ProdSelect.options;
	var OptLength = OptArr.length;
	for(index = 1; index < OptLength; index++){
		if(OptArr[index].className == 'prodOfMan_'+ManID || OptArr[index].className == 'prodOfMan_' || ManID == 0){
			OptArr[index].style.color = '#000000';
			OptArr[index].style.display = 'block';
		}
		else{
			OptArr[index].style.width = '500px';
			OptArr[index].style.color = "#FFFFFF";
		}
	}
}

function orderRadiosSelected(){
	var form = $('OrderDetails');
	var count = 0;
   form.getInputs('radio').each(function(s) {
		if(s.checked){
			count++
		}
	});
   if (count < 4) {
		alert('Aveti cel putin o eroare in completarea formularului ! \nVa rugam sa selectati din fiecare categorie cate o optiune ! \n (In cazul in care nu ati introdus o adresa de livrare comanda nu poate fi validata. Verificati zona rosie!) \n \nAtentie ! Comanda nu poate fi validata fara toate optiunile bifate !')
		return false
	} else {
	alert('Comanda a fost transmisa cu succes spre departamentul de vanzari. Va rugam sa va verificati casuta postala. Veti primi un e-mail in cateva minute. Daca din diverse motive nu primiti e-mailul va rugam sa ne contactati la numerele de telefon afisate pe pagina de contact. Multumim!')
	return true
	}
}
	
function orderRadiosSelected2(){
   var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
   var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
   var form = $('OrderDetails');
   var group = document.OrderDetails.shippingmethods;
   var group2 = document.OrderDetails.paymentmethods;
     for (var i=0; i<group.length; i++) {
       if (group[i].checked)
          break;
     }
     if (i==group.length){
       alert("Nu ati selectat metoda de transport");
	   return false
	  }else{
		for (var i=0; i<group2.length; i++) {
			if (group2[i].checked)
			break;
		}
		if (i==group2.length){
			alert("Nu ati selectat metoda de plata");
			return false
		}else{
			var name = document.OrderDetails.familyname.value;
			var email = document.OrderDetails.email.value;
			var errors = [];
			if (!ck_name.test(name) || name==null || name=="") {
				errors[errors.length] = "Va rugam sa va completati numele de familie.";
			}
			if (!ck_email.test(email) || email==null || email=="") {
				errors[errors.length] = "Adresa de email nu este valida.";
			}   
			if (errors.length > 0) {
				reportErrors(errors);
			} else {
				 $('#OrderDetails').submit();
				alert('Comanda a fost transmisa cu succes spre departamentul de vanzari. Va rugam sa va verificati casuta postala. Veti primi un e-mail in cateva minute. Daca din diverse motive nu primiti e-mailul va rugam sa ne contactati la numerele de telefon afisate pe pagina de contact. Multumim!')
			}	
		}
	 }
}
	
	
function reportErrors(errors){
 var msg = "Va rugam sa introduceti date valide...\n";
 for (var i = 0; i<errors.length; i++) {
 var numError = i + 1;
  msg += "\n" + numError + ". " + errors[i];
}
 alert(msg);
 return false
}



var newwindow;
function winPopUp(url,width,height)
{
	newwindow=window.open(url,'popup','height='+height+',width='+width+',status=yes,resizable=yes');
	if (window.focus) {newwindow.focus()}
	//newwindow.show()
	newwindow.focus();
}
function createCookie(name,value,days) {

	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function sendme()
{
	window.open("/tools/tools.php?addSubscr=new","NSWin","width=500,height=300,toolbar=0");
	var a = window.setTimeout("document.Newsletter.submit();",500);
}

function getCities(countryID){
	var	URL = '/tools/tools.php?Ajax=getCities';
	var SelectBox = $('userState');
	SelectBox.options.length = 0;
	SelectBox.options[SelectBox.options.length] = new Option(SiteLang['Loading'],'');

	var opt = {
		method: 'post',
		parameters:'countryID='+countryID,
		onSuccess: function(transport) {
			SelectBox.options.length = 0;
			eval(transport.responseText);
			//alert(transport.responseText);
			//$('userState').innerHTML = transport.responseText;
		},
		onFailure: function(t) {
			alert('Error ' + t.status + ' -- ' + t.statusText + '\n' + SiteLang['Contact_Sys_Admin']);

		}
	}
	new Ajax.Request(URL, opt);

}

function validateSelect(elm){
	if(elm.options[elm.selectedIndex].className == 'disabled'){
		alert(elm.options[elm.selectedIndex].text + ' ' + SiteLang['has_Subcategs'])
		elm.selectedIndex = elm.defaultSelected;
	}
}

function updateLangCode(lang_code){
	var langValue = $F('langcode_' + lang_code)
	var	URL = '/admin/language.php';
	var opt = {
		method: 'post',
		parameters:'update_code='+lang_code+'&update_value='+langValue,
		onLoading: function(transport) {
			$('img_'+lang_code).src = '/images/loading.gif';
		},

		onSuccess: function(transport) {
			$('img_'+lang_code).src = '/images/update.gif';
		},
		onFailure: function(t) {
			$('img_'+lang_code).src = '/images/error.gif';
			alert('Error ' + t.status + ' -- ' + t.statusText + '\n' + SiteLang['Contact_Sys_Admin']);
		}
	}
	new Ajax.Request(URL, opt);
}

function confirmURL(mess) {
	return confirm(mess);
}

function confirmSubmit(){
	var agree=confirm('Sunteti sigur?');
	if (agree)	return true ;
	else return false ;
}

function extractNumber(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;

	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}

	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}

	obj.value = temp;
}

function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;

	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}

	if (isNaN(key)) return true;

	keychar = String.fromCharCode(key);

	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;

	return isFirstN || isFirstD || reg.test(keychar);
}

function reloadCaptcha(){
	var captImg = $('captImg');
	captImg.src = captImg.src + '#';
	//captImg.src = captImg.src + '?'+rand(); // use this for opera
}

function rand()
{
	var now=new Date()
	var num=(now.getSeconds())%10
	var num=num+1
	return num;
}

function toogleTextArea(textareaid){
	if($(textareaid).rows <= 1) {
		$(textareaid).rows = 5;
		$(textareaid).cols = 50;
	}
	else{
		$(textareaid).rows  = 1;
		$(textareaid).cols  = 25;
	}
}

function confirmation() {
	var answer = confirm("Acest produs nu este disponibil momentan. Produsul nu poate fi livrat intr-un termen rezonabil de minim o saptamana, deoarece lipseste din stocurile furnizorilor. \n   - Va rugam sa alegeti un produs similar, dar disponibil, din listele noastre apasand OK. \n   - Daca doriti sa retinem comanda Dvs. pe o lista de asteptare, fara promisiunea ca vom putea aduce produsul, apasati Cancel.")
	if (answer){return false;}
	else{}
}

function check(shippingmethods, gpret) {
// Tip Plati 4 = Online, 5 = OP, 6 = Ramburs, 7 = Cash sau POS, 8 = Cash //
// Tip Transporturi 1,2,3,4,12 = Magazine, 6 = Cargus Standard, 7 = Cargus Ramburs, 11 = Coletarie Anuntata, 14 = FAN RAMBURS, 13 = FAN STANDARD//
	//alert(gpret);
	if (gpret == 0) {
		if (shippingmethods == 1 || shippingmethods == 2 || shippingmethods == 3 || shippingmethods == 4 || shippingmethods == 12){
			document.getElementById("7").checked = true;
			document.getElementById("7").disabled = false;
			document.getElementById("4").disabled = true;
			document.getElementById("5").disabled = false;
			document.getElementById("6").disabled = true;
			}
		else if  (shippingmethods == 7 || shippingmethods == 14) {
			document.getElementById("6").checked = true;
			document.getElementById("6").disabled = false;
			document.getElementById("4").disabled = true;
			document.getElementById("5").disabled = true;
			document.getElementById("7").disabled = true;
			}
		else {
			document.getElementById("5").checked = true;
			document.getElementById("5").disabled = false;
			document.getElementById("4").disabled = false;
			document.getElementById("6").disabled = true;
			document.getElementById("7").disabled = true;
			}
	} else {
		if (shippingmethods == 1 || shippingmethods == 2 || shippingmethods == 3 || shippingmethods == 4 || shippingmethods == 12){
			document.getElementById("8").checked = true;
			document.getElementById("8").disabled = false;
			document.getElementById("6").disabled = true;
			document.getElementById("4").disabled = true;
			document.getElementById("5").disabled = false;
			}
		else if  (shippingmethods == 7 || shippingmethods == 14) {
			document.getElementById("6").checked = true;
			document.getElementById("6").disabled = false;
			document.getElementById("5").disabled = true;
			document.getElementById("8").disabled = true;
			document.getElementById("4").disabled = true;
			}
		else if (shippingmethods == 11) {
			document.getElementById("5").checked = true;
			document.getElementById("5").disabled = false;
			document.getElementById("6").disabled = true;
			document.getElementById("4").disabled = true;
			document.getElementById("8").disabled = true;
			}
		else {
			document.getElementById("5").checked = true;
			document.getElementById("5").disabled = false;
			document.getElementById("6").disabled = true;
			document.getElementById("4").disabled = false;
			document.getElementById("8").disabled = true;
			}
	}	
}


function activateprodtabs(divid)
{
		var divArr = ['primaryinfo', 'otherinfos', 'prodcomments', 'prodrelateditems'];
		for (var ind = 0; ind < divArr.length; ++ind) {
			var buttonName = 'a_'+divArr[ind];
			if(divid == divArr[ind]){
				if($(divArr[ind])){
					$(divArr[ind]).show();
					$(divArr[ind]).style.visibility="visible";
					if ($(buttonName)) $(buttonName).addClassName('selected');
				}
			}
			else{
				if($(divArr[ind])){
					$(divArr[ind]).hide();
					$(divArr[ind]).style.visibility="hidden";
					if ($(buttonName)) $(buttonName).removeClassName('selected');
				}
			}
		}
}


