str_host = "[0-9a-zA-Z]+(\.[-0-9a-zA-Z]+)+";
str_email = "[-_.0-9a-zA-Z]+([+][-_.0-9a-zA-Z]+)*@"+str_host;
pcre_email = new RegExp("^"+str_email+"$");

var elems = document.getElementsByTagName( 'base' );
var url_base = elems[0].href;

var divw=0;
var divh=0;

// functie generala de popup:
function LoadPopupBase( url, w, h, namepop )
{
	if (!w) w=400;
	if (!h) h=400;
	if (!namepop) namepop="Popup";
  	win = window.open( url, namepop, 'scrollbars=yes, status=no, toolbar=0,menubar=0,titlebar=0,resizable=0, dependent=1, z-lock=1, width='+w+',height='+h );

	if ( !win )
	{
		alert('It appears that pop-up blockers are enabled on your computer, which may prevent\nsome components from functioning properly. Please temporarily disable any\npop-up blockers.\n\nTo disable the Windows XP pop-up blocker, from the Tools menu in Internet Explorer,\nselect Pop-up Blocker, then Turn Off Pop-up Blocker. To disable other pop-up blockers\nthat are part of a search engine or toolbar, right-click on a toolbar in Internet Explorer\nand click to deselect all toolbars except Standard Buttons, Address Bar, and Links.');
	}
	else
	{
		win.moveTo( screen.width/2-w/2, screen.height/2-h/2);
		win.focus();
	}
}

function check_login(email, pass)
{
	var e = document.getElementById(email).value;
	var p = document.getElementById(pass).value;
	
	if(!e)
	{
		alert("Va rugam introduceti adresa de mail");
		return false;
	}
	
	if ( !pcre_email.test( e ) )
	{
		alert('Adresa de email este invalida!');
		return false;
	}
	
	if( !p )
	{
		alert("Va rugam introduceti parola");
		return false;
	}
	return true;
}
function slideSubcategory(id, type)
{
	$('li#li' + id).slideToggle('slow');
	var on = $$("on"+id);
	var off = $$("off"+id);
	
	if( type == "on" )
	{
		on.style.display = "none";
		off.style.display = "block";
	}
	else
	{
		on.style.display = "block";
		off.style.display = "none";
	}
}

 
this.imagePreview = function(){
	
	$("a.zoom").hover(function(e){		

		var prod_id = this.id;
		
		$("body").append("<div id='preview'><img src='"+ this.rel +"' alt='Image preview' /></div>");	
		
		iw=$$("width_"+prod_id).value;
		ih=$$("height_"+prod_id).value;
		
		divw = parseInt(iw) + 15;
		divh = parseInt(ih) + 100;		
		followmouse(e);	
    },
	function(){
		$("#preview").remove();
    });	
	$("a.zoom").mousemove(function(e){followmouse(e);});
			
};

function truebody()
{
	return (!window.opera && document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function followmouse(e)
{
	var docwidth=document.all? truebody().scrollLeft+truebody().clientWidth : pageXOffset+window.innerWidth-15
	var docheight=document.all? Math.min(truebody().scrollHeight, truebody().clientHeight) : Math.min(document.body.offsetHeight, window.innerHeight)
if(typeof e != "undefined")
	{
	if(docwidth < 15+e.pageX+divw)
		xcoord = e.pageX-divw-5;
	else
		xcoord = 15+e.pageX;
	if(docheight < 15+e.pageY+divh)
		ycoord = 15+e.pageY-Math.max(0,(divh + e.pageY - docheight - truebody().scrollTop - 30));
	else
		ycoord = 15+e.pageY;
	}
else if (typeof window.event != "undefined")
	{
	if(docwidth < 15+truebody().scrollLeft+event.clientX+divw)
		xcoord = truebody().scrollLeft-5+event.clientX-divw;
	else
		xcoord = truebody().scrollLeft+15+event.clientX;

	if(docheight < 15+truebody().scrollTop+event.clientY+divh)
		ycoord = 15+truebody().scrollTop+event.clientY-Math.max(0,(divh + event.clientY - docheight - 30));
	else
		ycoord = truebody().scrollTop+15+event.clientY;
	}
	
	$("#preview")
			.css("left", xcoord + "px")
			.css("top", ycoord + "px")
			.fadeIn("fast");			
}

function GalleryPreview(img)
{	
	document['poza_large'].src=img;	    		
};

function setStyle(objId, style, value) {
    document.getElementById(objId).style[style] = value;
}

function copyValue(source, destination, def_value)
{
    if (document.getElementById(source).value == "") {
        fillSearch(source, def_value);
    } else {
        document.getElementById(destination).value = document.getElementById(source).value;
    }
}

// This function clears the search area
function clearSearch(container, real, def_val)
{
    var searchObj = document.getElementById(container);
    if (searchObj.value == def_val || searchObj.value == "") {
        document.getElementById(real).value = "";
        searchObj.value = "";
    }
}

function fillSearch(container, def_val)
{
    var searchObj = $$(container);
    if (searchObj.value == "") {
        	
        searchObj.value = def_val;
    }
}

function checkSearch()
{
   var val = $$('real_search').value;

    if( !val || val == 'denumire produs' )
    {
        alert("Introduceti textul cautat");
        return false;
    }

    var frm = $$("search_form");
    frm.elements['bt_submit'] = null;
    frm.submit();

    return false;
}

function checkNews(event, tip)
{
   if( (tip == 1 && event.keyCode == 13 ) || tip == 0 )
   {
		var val = $$('real_news').value;

	    if( !val )
	    {
	        alert("Introduceti adresa de e-mail");
	        return false;
	    }
		
		if ( !pcre_email.test( val ) )
		{
			alert('Adresa de email este invalida!');
			return false;
		}

	    var url = "server/register_to_newsletter.php?mail=" + val;
		setTimeout( 'make_news_request("'+url+'")' , 10 );

	    return true;
   }
   
}

var can_make_request = true;

function model_can_request()
{
	can_make_request = true;
}

function make_news_request( url )
{
	if ( can_make_request )
	{
		can_make_request = false;
		$.get(url,
		    function(data)
    		{
    		    var div = $$("msg_news");
				
				switch( data )
				{
					case '0':
						div.innerHTML = "Adresa de email deja inregistrata";
						div.className = "mesaj_newsletter_err";
					break;
					case '1':
						div.innerHTML = "Adresa de email inregistrata cu succes.";
						div.className = "mesaj_newsletter";
					break;
				}
                setTimeout( "model_can_request()" , 10 );
    		}
		);
	}
	else
	{
		setTimeout( 'make_news_request("'+url+'")' , 10 );
	}
}

function setCantValue( id )
{
	var input = $$( id );
	
	if( !isNaN( parseInt(input.value) ) && parseInt( input.value ) != 0 )
	{
		input.value = parseInt(input.value);
	}
	else
	{
		input.value = 1;
	}
}

function afiseaza_text( div, click, retrage, tip )
{
	$('div#' + div).slideToggle('blind');
	if( tip == 1 )
	{
		$$( click ).style.display = "none";
		$$( retrage ).style.display = "block";
	}
	else
	{
		$$( click ).style.display = "block";
		$$( retrage ).style.display = "none";
	}
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

function view_number( number, type )
{
	if( typeof type == 'undefined' )
	{
		var type = 'float';
	}

    if ( type == 'float' )
    {
        number = parseFloat(number);
        return number_format(number, 2, ',', '.');
    }
    else
    {
        number = parseInt(number);
        return number_format(number, 0, ',', '.');
    }
}

function comanda_make_request( url )
{
	if ( can_make_request )
	{
		can_make_request = false;
		$.get(url,
		    function(data)
    		{
    		   	if ( !data )
				{
					setTimeout( "model_can_request()" , 10 );
					return;
				}

				var values = data.split( "|||", 2 );

				var cnr = $$('cos_nr');
				if ( cnr )
				{
					cnr.innerHTML = values[1];
				}
				var cval = $$('cos_valoare');
				if ( cval )
				{
					cval.innerHTML = values[0];
				}

				if ( !current_pid_ordered )
				{
					return false;
				}

				window.location.href = url_base + "cos-cumparaturi.html";
				setTimeout( "model_can_request()" , 10 );
    		}
		);
	}
	else
	{
		setTimeout( 'comanda_make_request("'+url+'")' , 10 );
	}
}
var current_pid_ordered = 0;
function update_cart( pid, cant )
{
	// create url:
	current_pid_ordered = pid;
	url = "server/update_cos.php?prod_id=" + pid + "&cant=" + cant;
	setTimeout( 'comanda_make_request("'+url+'")' , 10 );
}

// starting the script on page load
$(document).ready(function(){
	imagePreview();
});

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
} 

function loadOrase(id)
{
	var judet = $$(id + "_judet").value;
		
	$.ajax({
		type: "POST",
		url: "server/schimba_localitatea.php",
		data: "judet_id=" + judet,
		success: function(resp){
			if(resp != ''){
				var $jsonResp = new Object();
				eval('$jsonResp = ' + resp);

				// empty select;
				$('select[name="' + id + '_oras"]').
				find('option').
				remove();

				// repopulate select
				var $selectHTML = '';
				for(option in $jsonResp){
					eval('var $value = $jsonResp.' + option + '.value; var $text = $jsonResp.' + option + '.text;');
					$selectHTML += '<option value="' + $value + '">' + $text + '</option>';
				}

				$('select[name="' + id + '_oras"]').append($selectHTML);
                
                return true;
			}
		}
	});
}
if (/msie/i.test (navigator.userAgent)) //only override IE
{
  document.nativeGetElementById = document.getElementById;
  document.getElementById = function(id)
  {
    var elem = document.nativeGetElementById(id);
    if(elem)
    {
      //make sure that it is a valid match on id
      if(elem.attributes['id'].value == id)
      {
        return elem;
      }
      else
      {
        //otherwise find the correct element
        for(var i=1;i<document.all[id].length;i++)
        {
          if(document.all[id][i].attributes['id'].value == id)
          {
            return document.all[id][i];
          }
        }
      }
    }
    return null;
  }
}

var $$ = function(id) { return document.getElementById(id); };
var $$false = function() { return false; };
