//<![CDATA[
$().ready(function() {
	$("#pasul_1").submit(function(){

        dataString = $("#pasul_1").serialize();
		$.ajax({
		type: "POST",
		url: "http://www.litera.ro/ajaxservice.do" + "?req=finishorder&step=1",
		data: dataString,
		dataType: "json",
		success: function(data) {
			if(data.status == "false"){
				$("#pasi_ajaxresponse").html("<div class='errorMessage nomg'>" + data.message + "</div>");
			} else {
				//$("#pasi_ajaxresponse").html("<div class='successMessage nomg'>" + data.message + "</div>");
				$('#pasul_1').replaceWith(data.newcontent);

				if(data.registered!='not') {
					$('#loginFormSelfReplace').replaceWith(data.registered);
                    $('#loggedInname').html(data.prenume);
					$('#notloggedInDIV').hide();
					$('#loggedInDIV').show();
					$('#loginForm').slideUp();
					$('td.nologgedin').remove();
					$('#logoutBar').show();
					atasezPasul_doi();
				}
			}
		}
		});
		return false;
	});


	// change filter by name/data
	$('.filterlisting').change(function() {
		var newlocation= $(this).val();
		window.location = newlocation;
	});




	//DICTIONAR - this script is used for dictionar suggestions
	function findValue(li) {
		//if( li == null ) return alert("No match!");
		// if coming from an AJAX call, let's use the CityId as the value
		if( !!li.extra ) var sValue = li.extra[0];
		// otherwise, let's just display the value in the text box
		else var sValue = li.selectValue;
		document.getElementById('cautare_dictionar').value = sValue;
		document.getElementById('formDictionar').submit();
		//alert("The value you selected was: " + sValue);
	}

	function selectItem(li) {
		findValue(li);
	}

	function formatItem(row) {
		return row[0] ;
	}

    function lookupAjax(){
		var oSuggest = $("#cautare_dictionar")[0].autocompleter;
		oSuggest.findValue();
		return false;
	}

	$("#cautare_dictionar").autocomplete(
		"http://www.litera.ro/ajax/dictionar/now/getList.html",
		{
			delay:10,
			minChars:2,
			matchSubset:1,
			mustMatch: false,
			matchContains:0,
			cacheLength:10,
			onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
			autoFill:true
		}
	);



//CARTI - this script is used for books search suggestions..
function matchText(value) {
	value.replace(/[^<]*(<a href='([^']+)'>([^<]+)<\/a>)/g, function () {
		window.location=Array.prototype.slice.call(arguments, 2, 3);
		});

  var re = new RegExp("\bt[a-zA-Z0-9\/\-]+\b");
  var m = re.exec(value);
  if (m == null) {
  } else {
    var s = "";
    for (i = 0; i < m.length; i++) {
		alert(m[i]);
      window.location = m[i];
    }
  }
}
function stripHTML(oldString) {

   var newString = "";
   var inTag = false;
   for(var i = 0; i < oldString.length; i++) {
   
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
              if(oldString.charAt(i+1)=="<")
              {
              		//dont do anything
	}
	else
	{
		inTag = false;
		i++;
	}
        }
   
        if(!inTag) newString += oldString.charAt(i);

   }

   return newString;
}
	function findValue2(li) {
		//if( li == null ) return alert("No match!");
		// if coming from an AJAX call, let's use the CityId as the value
		if( !!li.extra ) var sValue = li.extra[0];
		// otherwise, let's just display the value in the text box
		else var sValue = li.selectValue;
		
		if(sValue != 'cauta carte' && sValue !== undefined) {
			if (sValue.indexOf('<a')!=-1) {
				matchText(sValue);
				sValue = stripHTML(sValue);
				document.getElementById('cautare_carte').value = sValue;
				}
			else {
				document.getElementById('cautare_carte').value = sValue;
				document.getElementById('formCarte').submit();
				}
		}
		//alert("The value you selected was: " + sValue);
	}

	function selectItem2(li) {
		findValue2(li);
	}

	function formatItem2(row) {
		return row[0] ;
	}

	function lookupAjax2(){
		var oSuggest = $("#cautare_carte")[0].autocompleter;
		oSuggest.findValue2();
		return false;
	}
	
	//modif by dan: changed autoFill from true to false (below)
	$("#cautare_carte").autocomplete(
		"http://www.litera.ro/ajax/carte/now/getList.html",
		{
			delay:300,
			minChars:3,
			matchSubset:1,
			mustMatch:0,
			matchContains:true,
			cacheLength:0,
			onItemSelect:selectItem2,
			onFindValue:findValue2,
			formatItem:formatItem2,
			autoFill:false,
			max:15
		}
	);


	//
	var mouse_inside=false;
	var timeout=null;
	$('#loginForm').hover(function(){
		if (timeout!=null)
			clearTimeout(timeout);
		mouse_inside=true; 
	}, function(){ 
		if (timeout!=null)
			clearTimeout(timeout);
		timeout=setTimeout("hideAllBoxes();",5000);
		mouse_inside=false; 
	});
	$('#recoverPasswordForm').hover(function(){
		if (timeout!=null)
			clearTimeout(timeout);
		mouse_inside=true; 
	}, function(){ 
		if (timeout!=null)
			clearTimeout(timeout);
		timeout=setTimeout("hideAllBoxes();",5000);
		mouse_inside=false; 
	});
	$('#registerForm').hover(function(){
		if (timeout!=null)
			clearTimeout(timeout);
		mouse_inside=true; 
	}, function(){ 
		if (timeout!=null)
			clearTimeout(timeout);
		timeout=setTimeout("hideAllBoxes();",5000);
		mouse_inside=false; 
	});
	$('#selectCurrency').hover(function(){
		if (timeout!=null)
			clearTimeout(timeout);
		mouse_inside=true; 
	}, function(){ 
		if (timeout!=null)
			clearTimeout(timeout);
		timeout=setTimeout("hideAllBoxes();",5000);
		mouse_inside=false; 
	});
	$('#manageShoppingCart').hover(function(){
		if (timeout!=null)
			clearTimeout(timeout);
		mouse_inside=true; 
	}, function(){ 
		if (timeout!=null)
			clearTimeout(timeout);
		timeout=setTimeout("hideAllBoxes();",5000);
		mouse_inside=false; 
	});
	$('#notloggedInDIV').click(function(){mouse_inside=true;});
	$('#iforgotmypass').click(function(){mouse_inside=true;});
	$('#nologgedin').click(function(){mouse_inside=true;});
	$('#currencytd').click(function(){mouse_inside=true;});
	$('#manageShoppingCartTD').click(function(){mouse_inside=true;});

	$(document).click(function(){ 
		if (timeout!=null)
			clearTimeout(timeout);
		if(!mouse_inside) hideAllBoxes();
	});

	
	// Login FORM
	// attach here the event for "autentificare"
	$('td.td_user').click( function(){
		if ($("div#loginForm").is(":hidden")) {
			hideAllboxesfloatbar('div#loginForm');
			$("div#loginForm").slideDown();
		} else {
			$("div#loginForm").slideUp();
		}
		$("#loginFormAjax").html('');
		return false;
	});
	// autentificare btn close action
	$("#loginFormClose").click( function() {
		$("div#loginForm").slideUp();
	});
	// on blur / on focus ... value for input fields at login form
	$('#loginFormEmail').focus(function() {
		$(this).css('color','#343434');
		var localval = $('#loginFormEmail').val();
		if(localval=='Email')
			$('#loginFormEmail').val('');
	}); // blur
		$('#loginFormEmail').blur(function() {
			var localval = $('#loginFormEmail').val();
			if(localval=='') {
				$('#loginFormEmail').val('Email');
				$(this).css('color','#999999');
				}
		});
	$('#loginFormPassword').focus(function() {
		$(this).css('color','#343434');
		$('#loginFormPassword').replaceWith('\<input type="password" id="loginFormPassword" name="password" size="30" value="" /\>');
		$('#loginFormPassword').focus();
	}); // no more blur for password...

	// atasam evenimentul submit pentru.. login cu AJAX!
    $(function(){
        $("#loginFormBar").submit(function(){
            dataString = $("#loginFormBar").serialize();
            $.ajax({
            type: "POST",
            url: "http://www.litera.ro/ajaxservice.do",
            data: dataString,
            dataType: "json",
            success: function(data) {
                if(data.status == "false"){
                    $("#loginFormAjax").html("<div class='errorMessage'>" + data.message + "</div>");
                } else {
					$('#loginFormSelfReplace').replaceWith(data.newcontent);
                    $("#loginFormAjax").html("<div class='successMessage'>" + data.message + "</div>");
                    $('#loggedInname').html(data.prenume);
					$('#notloggedInDIV').hide();
					$('#loggedInDIV').show();
                    $("#loginFormAjax").html("<div class='successMessage'>" + data.message + "</div>");
					$('#loginForm').slideUp();
					$('td.nologgedin').remove();
					$('#logoutBar').show();
					if(data.refresh_page == 1) {
						window.location.reload(true);
					}
                }
            }
            });
            return false;            
        });
    });
		// HOLD on.. here we put the recover password code...
			// attach here the event for "autentificare"
			$('a#iforgotmypass').click( function(){
				$('#loginForm').slideUp();
				if ($("div#recoverPasswordForm").is(":hidden")) {
					hideAllboxesfloatbar('div#recoverPasswordForm');
					$("div#recoverPasswordForm").slideDown();
				} else {
					$("div#recoverPasswordForm").slideUp();
				}
				$("#recoverPasswordFormAjax").html('');
				return false;
			});
			// recoverPassword btn close action
			$("#recoverPasswordFormClose").click( function() { 
				$("div#recoverPasswordForm").slideUp();
			});
			// on blur / on focus ... value for input fields at login form
			$('#recoverPasswordFormEmail').focus(function() {
				$(this).css('color','#343434');
				var localval = $('#recoverPasswordFormEmail').val();
				if(localval=='Email')
					$('#recoverPasswordFormEmail').val('');
			}); // blur
				$('#recoverPasswordFormEmail').blur(function() {
					var localval = $('#recoverPasswordFormEmail').val();
					if(localval=='') {
						$(this).css('color','#999999');
						$('#recoverPasswordFormEmail').val('Email');
					}
				});

			// atasam evenimentul submit pentru.. recover password cu AJAX!
			$(function(){
			    $("#recoverPasswordBar").submit(function(){
			        dataString = $("#recoverPasswordBar").serialize();
			        $.ajax({
			        type: "POST",
			        url: "http://www.litera.ro/ajaxservice.do",
			        data: dataString,
			        dataType: "json",
			        success: function(data) {
			            if(data.status == "false"){
			                $("#recoverPasswordFormAjax").html("<div class='errorMessage'>" + data.message + "</div>");
			            } else {
			                $("#recoverPasswordFormAjax").html("<div class='successMessage'>" + data.message + "</div>");
			            }
			        }
			        });
			        return false;            
			    });
			});
		// end of recover password code
		
	// END of Login FORM


	// Register FORM
	// attach here the event for "register"
	$('td.nologgedin').click( function(){

		if ($("div#registerForm").is(":hidden")) {
			hideAllboxesfloatbar('div#registerForm');
			$("div#registerForm").slideDown();
		} else {
			$('.ui-notification-container').remove();
			$("div#registerForm").slideUp();
		}
		$("#registerFormAjax").html('');
		return false;
	});
	// register btn close action
	$("#registerFormClose").click( function() { 
		hideAllboxesfloatbar();
		$('.ui-notification-container').remove();
		$("div#registerForm").slideUp();
	});
	// on blur / on focus ... value for input fields at login form
	$('#registerFormEmail').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormEmail').val();
		if(localval=='Email')
			$('#registerFormEmail').val('');
	}); // blur
		$('#registerFormEmail').blur(function() {
			var localval = $('#registerFormEmail').val();
			if(localval=='') {
				$('#registerFormEmail').val('Email');
				$(this).css('color','#999999');
			}
			else $('#registerFromPassword').focus();
		});
	$('#registerFormPassword1').focus(function() {
		$('#registerFormPassword1').replaceWith('\<input type="password" id="registerFormPassword1" name="password1" style=" width:185px" value="" /\>');
		$('#registerFormPassword1').focus();
	}); // no more blur for password...
	$('#registerFormPassword').focus(function() {
		$('#registerFormPassword').replaceWith('\<input type="password" id="registerFormPassword" name="password" style=" width:185px" value="" /\>');
		$('#registerFormPassword').focus();
	}); // no more blur for password...
	$('#registerFormNume').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormNume').val();
		if(localval=='Nume')
			$('#registerFormNume').val('');
	}); // blur
		$('#registerFormNume').blur(function() {
			var localval = $('#registerFormNume').val();
			if(localval=='') {
				$(this).css('color','#999999');
				$('#registerFormNume').val('Nume');
			}
		});

	$('#registerFormPrenume').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormPrenume').val();
		if(localval=='Prenume')
			$('#registerFormPrenume').val('');
	}); // blur
		$('#registerFormPrenume').blur(function() {
			var localval = $('#registerFormPrenume').val();
			if(localval=='') {
				$(this).css('color','#999999');
				$('#registerFormPrenume').val('Prenume');
			}
		});

$('#registerFormBirthday').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormBirthday').val();
		if(localval=='Data nasterii (zz-ll-aaaa)')
			$('#registerFormBirthday').val('');
	}); // blur
		$('#registerFormBirthday').blur(function() {
			var localval = $('#registerFormBirthday').val();
			if(localval=='') {
				$(this).css('color','#999999');
				$('#registerFormBirthday').val('Data nasterii (zz-ll-aaaa)');
			}
		});

	$('#registerFormTelefon').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormTelefon').val();
		if(localval=='Telefon')
			$('#registerFormTelefon').val('');
	}); // blur
		$('#registerFormTelefon').blur(function() {
			var localval = $('#registerFormTelefon').val();
			if(localval=='') {
				$(this).css('color','#999999');
				$('#registerFormTelefon').val('Telefon');
			}
		});

	$('#registerFormCNP').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormCNP').val();
		if(localval=='CNP')
			$('#registerFormCNP').val('');
	}); // blur
		$('#registerFormCNP').blur(function() {
			var localval = $('#registerFormCNP').val();
			if(localval=='') {
				$(this).css('color','#999999');
				$('#registerFormCNP').val('CNP');
			}
		});


	$('#registerFormAdresa').focus(function() {
				$(this).css('color','#343434');
		var localval = $('#registerFormAdresa').val();
		if(localval=='Adresa')
			$('#registerFormAdresa').val('');
	}); // blur
		$('#registerFormAdresa').blur(function() {
			var localval = $('#registerFormAdresa').val();
			if(localval=='') {
				$(this).css('color','#999999');
				$('#registerFormAdresa').val('Adresa');
			}
		});




	// atasam evenimentul submit pentru.. register cu AJAX!
    $(function(){
        $("#registerFormBar").submit(function(){
            dataString = $("#registerFormBar").serialize();
            $.ajax({
            type: "POST",
            url: "http://www.litera.ro/ajaxservice.do",
            data: dataString,
            dataType: "json",
            success: function(data) {
                if(data.status == "false"){
                    $("#registerFormAjax").html("<div class='errorMessage'>" + data.message + "</div>");
                } else {
                    $("#registerFormAjax").html("<div class='successMessage'>" + data.message + "</div>");
					//$('#registerForm').slideUp();
					if (data.loggedin) {
						$('#loginFormSelfReplace').replaceWith(data.newcontent);
						$("#loginFormAjax").html("<div class='successMessage'>" + data.message + "</div>");
						$('#loggedInname').html(data.prenume);
						$('#notloggedInDIV').hide();
						$('#loggedInDIV').show();
						$("#loginFormAjax").html("<div class='successMessage'>" + data.message + "</div>");
						$('#loginForm').slideUp();
						$('td.nologgedin').remove();
						$('#logoutBar').show();
						}
					
                }
            }
            });
            return false;            
        });
    });

	function addNotice(e,opts) {
		if (e) {
			e.preventDefault();
		}
		opts = opts ? opts : {};
		$.noticeAdd($.extend({
			text: opts.text || "Notification",
			title: opts.title || "Notice"
		},opts));
	}

        if($('a#applyMembershipBar').length){
            
            var membershipTEXT;
            $.get('http://www.litera.ro/text_membership_de_ce.php', function(data) {
                    membershipTEXT = data;
            });
            $('a#applyMembershipBar').click(function(e){ addNotice(e,{text: ""+membershipTEXT+"", title: "De ce membru CLUB Litera?", stay: true}); });
        }
	

	$('#registerFormMembership').click(function() {
		if ($("#registerFormMembership").is(":checked")) {
			$("#membershipFields").show();
		} else {
			$("#membershipFields").hide();
		}
	});
	// END of Register FORM


	// change CURRENCY
	$('td#currencytd').click( function(){
		if($('div#selectCurrency').is(':hidden')) {
			hideAllboxesfloatbar('div#selectCurrency');
			$('div#selectCurrency').slideDown();
		} else {
			$('div#selectCurrency').slideUp();
		}
	});
	$("#selectCurrencyClose").click( function() { 
		$("div#selectCurrency").slideUp();
	});


	// manage Shopping cart
	$('td#manageShoppingCartTD').click( function(){
		//window.location = 'http://www.litera.ro/?pag=cos_new'; 
		
		if($('div#manageShoppingCart').is(':hidden')) {
			hideAllboxesfloatbar('div#manageShoppingCart');
			$('div#manageShoppingCart').slideDown();
		} else {
			$('div#manageShoppingCart').slideUp();
		}
		
	});
	$("#manageShoppingCartClose").click( function() { 
		$("div#manageShoppingCart").slideUp();
	});



	var div = new Array();
	// move left/right.. 
	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;}
	
	var animation=false;
	$(document).ready(function(){
		$("div.content_noutati div.btn_right_carti").click(function(){
		
			var tab_number = $(this).attr('title');
		
			$('div.btn_right_carti#right_'+tab_number).css('display','none');
			$('div.btn_left_carti#left_'+tab_number).css('display','block');
			
			var ids = new Array();
			var action = 'new';
			if ($(this).parent().parent().attr('class') == 'content_section_galben') {
				action = 'promo';
				}
			if ($(this).parent().parent().attr('class') == 'content_section_verde_inchis') {
				action = 'soon';
				}
			i=0;
			$(this).parent().parent().find('.unloaded').each(function(){
				ids[i] = $(this).attr('id');
				i++;
				});
			if (ids.length!=0) {
				$.ajax({
					type: "POST",
					url: "http://www.litera.ro/ajaxHomePage.php",
					data: {'action':action,'ids':ids},
					dataType: "json",
					success: function(data) {
						for (id in data) {
							$('#'+id).html(data[id]);
							$('#'+id).removeClass('unloaded');
							}
						}
					});
				}
			
			var carti_count		= 0;
			var holders_count	= 0;
			
			$(this).parent().find("div.overflow").each(function(){
				holders_count++;
				$(this).find("div.detalii_carte").each(function(){
					carti_count++;
					});
				});
			var count=carti_count/holders_count;
			var total_width=count*145;
			var left=$(this).parent().find("div.overflow").css('left');
			left=left.replace('-','');
			left=left.replace('px','');
			if (left=='auto')left=0;
			if (left+685<total_width) {
				if (left+1350>total_width) {
					var move=total_width-675-left+10;
					var rate=move/135*200;
					}
				else {
					var move=685;
					var rate=1000;
					}
				if (move!=0 && !animation) {
					animation=true;
					$(this).parent().find("div.overflow").animate({  left: "-="+move+"px" }, rate, 'linear', function(){ animation=false; } );
					}
				else if (move==0) {
					animation=false;
					}
				}
			});
		$("div.content_noutati div.btn_left_carti").click(function(){
		
		var tab_number = $(this).attr('title');
		
		$('div.btn_left_carti#left_'+tab_number).css('display','none');
		$('div.btn_right_carti#right_'+tab_number).css('display','block');
		
			var carti_count=0;
			var holders_count=0;
			$(this).parent().find("div.overflow").each(function(){
				holders_count++;
				$(this).find("div.detalii_carte").each(function(){
					carti_count++;
					});
				});
			var count=carti_count/holders_count;
			var total_width=count*135;
			var left=$(this).parent().find("div.overflow").css('left');
			left=left.replace('-','');
			left=left.replace('px','');
			if (left=='auto')left=0;
			if (left-1350<0) {
				var move=left;
				var rate=move/135*200;
				}
			else {
				var move=685;
				var rate=1000;
				}
			if (move!=0 && !animation) {
				animation=true;
				$(this).parent().find("div.overflow").animate({  left: "+="+move+"px" }, rate, 'linear', function(){ animation=false; } );
				}
			else if (move==0) {
				animation=false;
				}
			});
		
		});
	
	// OLD HOMEPAGE SCROLLERS
	/*$(document).ready(function(){
	// THE ACTION ON THE LEFT ARROW
	$("div.content_noutati div.btn_right_carti").hover(function(){
		var elemnts=$(this).parent().find("div.overflow > div").size();
		if (elemnts>5) {
			if($(this).parent().parent().attr('id') == 'promotii_homepage') { elemnts = parseInt(elemnts/2); }
			var div_width=elemnts*135-724+120;
			var arate=6;
			$(this).parent().find("div.overflow").stop();
			var mleft=$(this).parent().find("div.overflow").css('left');
			mleft=mleft.replace('-','');
			mleft=mleft.replace('px','');
			if (mleft=='auto')mleft=0;
			var width=div_width;
			width=width-mleft;
			$(this).parent().find("div.overflow").animate({  left: "-="+width+"px" }, arate*width, 'linear' );
			}
		},function(){$(this).parent().find("div.overflow").stop();});
	$("div.content_noutati div.btn_right_carti").click(function(){
		var elemnts=$(this).parent().find("div.overflow > div").size();
		if (elemnts>5) {
			if($(this).parent().parent().attr('id') == 'promotii_homepage') { elemnts = parseInt(elemnts/2); }
			var div_width=elemnts*135-724+120;
			var arate=0.1;
			$(this).parent().find("div.overflow").stop();
			var mleft=$(this).parent().find("div.overflow").css('left');
			mleft=mleft.replace('-','');
			mleft=mleft.replace('px','');
			if (mleft=='auto')mleft=0;
			var width=div_width;
			width=width-mleft;
			$(this).parent().find("div.overflow").animate({  left: "-="+width+"px" }, arate*width, 'linear' );
			}
		});
	// THE ACTION ON THE RIGHT ARROW
	$("div.content_noutati div.btn_left_carti").hover(function(){
		var elemnts=$(this).parent().find("div.overflow > div").size();
		if (elemnts>5) {
			if($(this).parent().parent().attr('id') == 'promotii_homepage') { elemnts = parseInt(elemnts/2); }
			var div_width=elemnts*135-724+120;
			var arate=6;
			$(this).parent().find("div.overflow").stop();
			var mleft=$(this).parent().find("div.overflow").css('left');
			mleft=mleft.replace('-','');
			mleft=mleft.replace('px','');
			//if (parseInt(mleft)<=0)
			//mleft=parseInt(mleft)+30;
			$(this).parent().find("div.overflow").animate({  left: "+="+mleft+"px" }, arate*mleft, 'linear' );
			}
		},function(){$(this).parent().find("div.overflow").stop();});
	$("div.content_noutati div.btn_left_carti").click(function(){
		var elemnts=$(this).parent().find("div.overflow > div").size();
		if (elemnts>5) {
			if($(this).parent().parent().attr('id') == 'promotii_homepage') { elemnts = parseInt(elemnts/2); }
			var div_width=elemnts*135-724+120;
			var arate=0.1;
			$(this).parent().find("div.overflow").stop();
			var mleft=$(this).parent().find("div.overflow").css('left');
			mleft=mleft.replace('-','');
			mleft=mleft.replace('px','');
			//if (parseInt(mleft)<=0)
			//mleft=parseInt(mleft)+30;
			$(this).parent().find("div.overflow").animate({  left: "+="+mleft+"px" }, arate*mleft, 'linear' );
			}
		});
	});*/
	

	// force numeric input la bucati
	$('.smallinputcos').numeric();
	$('.inputbbook').numeric();

	$('input.telefon').numeric({allow:".+"});
	$('input.cnp').numeric();


	// make all "cumpara" buttons to do the "buy" action by AJAX...
	// buttons are like: <a class="btn_carte" href="http://www.litera.ro/adauga_in_cos/ciresarii-vol-4-cid-522" title="Cumpara">Cumpara</a>
	$('a.btn_carte').click(function(){
		// fetch the link

		href = $(this).attr('href');
		href = href + '?ajax=enabled';
        $("#manageShoppingCartAjax").load(href, function() { fetchTheNewCart(); }); // load data from ajax
		// Open cart action moved to fetchTheNewCart
		return false;
	});	

	// validare newsletter email!
    $(function(){
        $("#abonareNewsletter").submit(function(){
			var email = $('input.adresa_news').val();
			if(emailValidate(email)==false)
            return false;
				else return true;
        });
    });



	// pentru notificari.. inchidere automata!
	// .successMessage | .errorMessage


	

});

	// remove a product from shopping cart
	function removeFromCart(key,t){
		// do a request...

        dataString = "req=removeProduct&product="+key;
        $.ajax({
        type: "POST",
        url: "http://www.litera.ro/ajaxservice.do",
        data: dataString,
        dataType: "json",
        success: function(data) {
            if(data.status == "false"){
                $("#manageShoppingCartAjax").html("<div class='errorMessage'>" + data.message + "</div>");
            } else {
				$('#manageShoppingCartContainer').replaceWith(data.newcontent);
                $("#manageShoppingCartAjax").html("<div class='successMessage'>" + data.message + "</div>");
				$('#howmanyprods').html(data.newproducts);
				// fetch the class
				var theclass = $(t).attr("class");
				if(theclass == 'del_btn') {
					$(t).parent().parent().replaceWith('');
				}
				if(document.getElementById('coshowmany'))
					$('#coshowmany').html(data.newproducts);

				if(document.getElementById('elem-'+key)) {
					$('#elem-'+key).replaceWith('');
				}

				setTimeout('updatePretTotal()',1000);
				returnEconomisit();
				updatePretLista();
            }
        }
        });

		return false;
	}

	// remove a product from shopping cart
	function fetchTheNewCart(){
		// do a request...

	        dataString = "req=fetchnewcart";
	        $.ajax({
	        type: "POST",
	        url: "http://www.litera.ro/ajaxservice.do",
	        data: dataString,
	        dataType: "json",
	        success: function(data) {
	            if(data.status == "false"){
	                $("#manageShoppingCartAjax").html("<div class='errorMessage'>" + data.message + "</div>");
	            } else {
					$('#manageShoppingCartContainer').replaceWith(data.newcontent);
	                $("#manageShoppingCartAjax").html("<div class='successMessage'>" + data.message + "</div>");
					$('#howmanyprods').html(data.newproducts);
					if(document.getElementById('coshowmany'))
						$('#coshowmany').html(data.newproducts);
						
					if($('div#manageShoppingCart').is(':hidden')) {
						hideAllboxesfloatbar('div#manageShoppingCart');
						$('div#manageShoppingCart').slideDown();
						$("#manageShoppingCart").attr({ scrollTop: $("#manageShoppingCart").attr("scrollHeight") });
						timeout=setTimeout("$('div#manageShoppingCart').slideUp();",5000);
						$('div#manageShoppingCart').click(function (){ if (timeout!=null)clearTimeout(timeout); });
						
						$('#change_button').html('<a title="Finalizare comanda" href="./vizualizare_cos/" OnClick="_gaq.push([\'_trackPageview\',\'/detalii-facturare\']);"> <img alt="Finalizare comanda" src="./css/images/fin_comanda.png" /> </a>');
						
						
						
				
						
						
						
					} else {
						// no need...
					}	
	            }
	        }
	        });
	        return false;            


	}

	function updateNumarProduse() {

	        dataString = "req=howmanyProducts";
	        $.ajax({
	        type: "POST",
	        url: "http://www.litera.ro/ajaxservice.do",
	        data: dataString,
	        dataType: "json",
	        success: function(data) {
	            if(data.status == "false"){
	                $("#manageShoppingCartAjax").html("<div class='errorMessage'>" + data.message + "</div>");
	            } else {
	                $("#manageShoppingCartAjax").html("<div class='successMessage'>" + data.message + "</div>");
					$('#howmanyprods').html(data.newproducts);
					if(document.getElementById('coshowmany'))
						$('#coshowmany').html(data.newproducts);
	            }
	        }
	        });
	        return false;            


	}

	function updatePretTotal() {
		$(function(){
	        dataString = "req=pretTotal";
	        $.ajax({
	        type: "POST",
	        url: "http://www.litera.ro/ajaxservice.do",
	        data: dataString,
	        dataType: "json",
	        success: function(data) {
	            if(data.status == "true"){
					if(document.getElementById('totalcos')) {
						$('#totalcos').html(data.totalprice);
					}
					// daca exista si #totalcos_total
					if(document.getElementById('totalcos_total')) {
						$('#totalcos_total').html(data.totalprice);
					}
	            }
	        }
	        });
	        return false;            

		});
	}

	function returnEconomisit(){
		$(function(){
	        dataString = "req=aiEconomisit";
	        $.ajax({
	        type: "POST",
	        url: "http://www.litera.ro/ajaxservice.do",
	        data: dataString,
	        dataType: "json",
	        success: function(data) {
	            if(data.status == "true"){
					if(document.getElementById('aieconomisit')) {
						$('#aieconomisit').html(data.aieconomisit);
					}

					// daca exista si #totaleconomisit_total
					if(document.getElementById('totaleconomisit_total')) {
						$('#totaleconomisit_total').html(data.aieconomisit);
					}
	            }
	            if(data.aieconomisit == 0) {
					$("#neconomisit").hide();
				} else {
					$("#neconomisit").show();
				}
	        }
	        });
	        return false;            

		});
	}


	function update_nrbucati(key,nr_bucati)
	{
		var request=MakeObject();
	
		request.open('get', 'http://www.litera.ro/returnant.php?tip=updatecos&key='+key+'&buc='+nr_bucati);
		request.send(false);
		
		if ($("#collection_"+key).html()=='98' || $("#collection_"+key).html()=='124')
		   {
		   window.location='http://www.litera.ro/vizualizare_cos';
		   return true;
		   }
		updateNumarProduse();
		setTimeout('updatePretTotal()',200);
		returnEconomisit();
		updatePretLista();
	}


	function updatePretLista() {
		//
		$(function(){
	        dataString = "req=pretLista";
	        $.ajax({
	        type: "POST",
	        url: "http://www.litera.ro/ajaxservice.do",
	        data: dataString,
	        dataType: "json",
	        success: function(data) {
	            if(data.status == "true"){
					// daca exista si #totaleconomisit_total
					if(document.getElementById('totallista_total')) {
						$('#totallista_total').html(data.pretLista);
					}
	            }
	        }
	        });
	        return false;            

		});
	}



	// ok, do some "TAB" stuff for Adulti/Copii
	function changesmalTab(type){
		if(type=='adult') {
			$('#bestseller_tab_adulti').show();
			$('#adulttitle').css('background-color','#FFFFFF').css('color','#5A5A5A').css('border-left','1px solid #e0e0e0');
			$('#bestseller_tab_copii').hide();
			$('#childtitle').css('background-color','#525252').css('color','#FFFFFF').css('border-right','0px');
		}
			else {

				$('#bestseller_tab_adulti').hide();
				$('#adulttitle').css('background-color','#525252').css('color','#FFFFFF').css('border-left','0px');
				$('#bestseller_tab_copii').show();
				$('#childtitle').css('background-color','#FFFFFF').css('color','#5A5A5A').css('border-right','1px solid #e0e0e0');
			}
	}


	function emailValidate(email) {
	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   if(reg.test(email) == false) {
		  return false;
	   } else return true;
	}


	function error(elem, text) {
			if (errfound) return;
			window.alert(text);
			elem.select();
			elem.focus();
			errfound = true;
	}

	function adresaCheck(f)
	{
		errfound = false;
		if (f.strada.value == "")
		{
			error(f.strada," STRADA - necompletat");
			errfound = true;
		}
		if (f.nr.value == "")
		{
			error(f.nr,"NUMAR - necompletat");
			errfound = true;
		}

		if (f.altaLocalitate.checked)
		{
			if (f.localitate.value == "")
			{
				error(f.localitate,"LOCALITATE - necompletat");
				errfound = true;
			}
			if (f.judet.value == "")
			{
				error(f.judet,"JUDET - necompletat");
				errfound = true;
			}
		}

		return !errfound;
	}

	function altaLocalitateClick(where)
	{
		combo = document.getElementById("altaLocalitate-"+where);
		if (combo.checked)
		{
			tr = document.getElementById("trLocalitate-"+where);
			//tr.disabled=false;

			tr.style.display="table-row";
			//tr = document.getElementById("inputJudet");
			//tr.disabled=false;

			tr = document.getElementById("inputOras-"+where);
			tr.disabled=true;
			tr = document.getElementById("inputLocalitate-"+where);
			//tr.disabled=false;
			tr.focus();

		}
		else
		{
			//tr = document.getElementById("inputLocalitate");
			//tr.disabled=true;
			tr = document.getElementById("trLocalitate-"+where);
			tr.style.display="none";
			//tr = document.getElementById("inputJudet");
			//tr.disabled=true;
			tr = document.getElementById("inputOras-"+where);
			tr.disabled=false;
		}

	}

	function editeazaAdresa(addresa) {
			if ($("div#"+addresa).is(":hidden")) {
				$("div#"+addresa).slideDown();
			} else {
				$("div#"+addresa).slideUp();
			}
		return false;
	}
	function saveAddr(adresa) {
		var adr = document.getElementById('showmeaddr-'+adresa);
		var serializez = '';
		var hasAlta = false;
		var cautInput = adr.getElementsByTagName('input');

		for(var i=0; i<cautInput.length; i++) {
			if(serializez == '' && cautInput[i].getAttribute('name')!='undefined' && cautInput[i])
				serializez = cautInput[i].getAttribute('name') + '=' + cautInput[i].value;
			else {

				if(cautInput[i].getAttribute('name')=='altaLocalitate' && cautInput[i].checked===true) {
					hasAlta = true;
				}
				if(hasAlta === false) {
					if(cautInput[i].getAttribute('name')!='localitate')
						serializez += '&' + cautInput[i].getAttribute('name') + '=' + cautInput[i].value;
				} else {
					serializez += '&' + cautInput[i].getAttribute('name') + '=' + cautInput[i].value;
				}
			}
		}
		if(hasAlta===false) {
			// reading the localitate
			var oras = document.getElementById('inputOras-'+adresa).value;
			serializez += '&oras=' + oras;
		}
		var tara = document.getElementById('selectTara').value;
		serializez += '&tara=' + tara;

		// update the Address
			serializez += '&req=updateAddr&id_adresa='+adresa;
            $.ajax({
            type: "POST",
            url: "http://www.litera.ro/ajaxservice.do",
            data: serializez,
            dataType: "json",
            success: function(data) {
		            if(data.status == "false"){
		                $("#pasi_ajaxresponse").html("<div class='errorMessage'>" + data.message + "</div>");
		            } else {
		                $("#pasi_ajaxresponse").html("<div class='successMessage'>" + data.message + "</div>");
						if(data.flagExtern!='1')
							$('#detspan-'+adresa).html(data.newaddress);
							else
							$('#newaddressReplace').replaceWith(data.addaddress);

							$('#showmeaddr--1').slideUp();

						//$('#loginFormSelfReplace').replaceWith(data.newcontent);
		            }
		        }
            });
		return false;
	}

	function finalizeazaComanda(){
		//$('#ajaxreturninfo')
		if($("#finalizeaza_clicked").attr('rel') != 'true') {
			$('#ajaxreturninfo').html('<img src="http://www.litera.ro/images/ajax_loader.gif" alt="Loading..." title="Se proceseaza comanda..." />');
			$('#lastfinalstep').hide();
		}
		var def = 'cash';
		if(document.getElementById('mcash').checked===false)
			def = 'epayment';
		if(document.getElementById('cod_cupon').checked===false)
			cod_cupon = document.getElementById('cod_cupon').value;

		metprec = $('input:radio[name=metoda_precomanda]:checked').val();

			serializez = 'req=finalizeazaComanda&metoda_plata='+def+'&metoda_precomanda='+metprec+'&cod_cupon='+cod_cupon;
            $.ajax({
            type: "POST",
            url: "http://www.litera.ro/ajaxservice.do",
            data: serializez,
            dataType: "json",
            success: function(data) {
		            if(data.status == "false"){
		                $("#pasi_ajaxresponse").html("<div class='errorMessage'>" + data.message + "</div>");
						$("#ajaxreturninfo").html('');
						$('#lastfinalstep').show();
		            } else {
		               // $("#pasi_ajaxresponse").html("<div class='successMessage'>" + data.message + "</div>");
			
						$('#ajaxreturninfo').html(data.finalcontent);
						$('#ajaxreturninfo').append('<iframe src="http://www.litera.ro/conversion_page.html" width="1" height="1"><p>Your browser does not support iframes.</p></iframe>');
		            }
					
					$("#finalizeaza_clicked").attr('rel','true');
		        }
            });
		

		return false;
	}


	function hideAllboxesfloatbar(whatcontainer) {
		

		// cel de login
		if(whatcontainer != 'div#loginForm') {
			if ($("div#loginForm").is(":hidden")) {
			} else {
				$("div#loginForm").hide();
			}
		}

		// forgot pass
		if(whatcontainer != 'div#recoverPasswordForm') {
			if ($("div#recoverPasswordForm").is(":hidden")) {
			} else {
				$("div#recoverPasswordForm").hide();
			}
		}
	
		// register form
		if(whatcontainer != 'div#registerForm') {
			if ($("div#registerForm").is(":hidden")) {
			} else {
				//$('.ui-notification-container').remove();
				$("div#registerForm").hide();
			}
		}

		// change currency
		if(whatcontainer != 'div#selectCurrency') {
			if($('div#selectCurrency').is(':hidden')) {
			} else {
				$('div#selectCurrency').hide();
			}
		}

		// shopping cart
		if(whatcontainer != 'div#manageShoppingCart') {
			if($('div#manageShoppingCart').is(':hidden')) {
			} else {
				$('div#manageShoppingCart').hide();
			}
		}
	}
	
	function hideAllBoxes() {
		// cel de login
			if ($("div#loginForm").is(":hidden")) {
			} else {
				$("div#loginForm").slideUp();
			}

		// forgot pass
			if ($("div#recoverPasswordForm").is(":hidden")) {
			} else {
				$("div#recoverPasswordForm").slideUp();
			}
	
		// register form
			if ($("div#registerForm").is(":hidden")) {
			} else {
				$("div#registerForm").slideUp();
			}

		// change currency
			if($('div#selectCurrency').is(':hidden')) {
			} else {
				$('div#selectCurrency').slideUp();
			}

		// shopping cart
			if($('div#manageShoppingCart').is(':hidden')) {
			} else {
				$('div#manageShoppingCart').slideUp();
			}
		}


var clearMessages=setInterval("checkMessages()",1000);
function checkMessages(){
	// here.. check the boxes if exists.. and then, after 3 seconds.. remove them
	if ( $('.successMessage').length!=0 && !$('.successMessage').is(":hidden")) {
		//  lasa-l asa
		var dostuff = setTimeout('closeMessages()',5000);
	}

	if ( $('.errorMessage').length!=0 && !$('.errorMessage').is(":hidden")) {
		var dostuff = setTimeout('closeMessages()',5000);
	}
}
function closeMessages(){
	if ($('.successMessage').is(":hidden")) {
		//  lasa-l asa
	} else {
		// inchide-l!
		$('.successMessage').slideUp();
	}

	if ($('.errorMessage').is(":hidden")) {
		//  lasa-l asa
	} else {
		// inchide-l!
		$('.errorMessage').slideUp();
	}
}






    $("#pasul_3").submit(function(){
		if ($("#showmeaddr--1").is(":hidden")) {
			}
		else {
			saveAddr('-1');
			}
        dataString = $("#pasul_3").serialize();
		$.ajax({
		type: "POST",
		url: "http://www.litera.ro/ajaxservice.do" + "?req=finishorder&step=3",
		data: dataString,
		dataType: "json",
		success: function(data) {
			if(data.status == "false"){
				$("#pasi_ajaxresponse").html("<div class='errorMessage nomg'>" + data.message + "</div>");
			} else {
				$("#pasi_ajaxresponse").html("<div class='successMessage nomg'>" + data.message + "</div>");
				$('#pasul_3').replaceWith(data.newcontent);
			}
		}
		});
		return false;
	});

//]]>

