
jQuery.cookie = function(name, value, options) {
    if(typeof name != 'undefined'){// name given, 
      if (typeof value != 'undefined') { // name and value given, set cookie
	  options = options || {};
	  if (value === null) {
	      value = '';
	      options.expires = -1;
	  }
	  var expires = '';
	  if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
	      var date;
	      if (typeof options.expires == 'number') {
		  date = new Date();
		  date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
	      } else {
		  date = options.expires;
	      }
	      expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
	  }
	  var path = options.path ? '; path=' + (options.path) : '';
	  var domain = options.domain ? '; domain=' + (options.domain) : '';
	  var secure = options.secure ? '; secure' : '';
	  document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
      } else { // only name given, get cookie
	  var cookieValue = null;
	  if (document.cookie && document.cookie != '') {
	      var cookies = document.cookie.split(';');
	      for (var i = 0; i < cookies.length; i++) {
		  var cookie = jQuery.trim(cookies[i]);
		  // Does this cookie string begin with the name we want?
		  if (cookie.substring(0, name.length + 1) == (name + '=')) {
		      cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
		      break;
		  }
	      }
	  }
	  return cookieValue;
      }
    }else{//get all cookie as array
	  var cookies = { };
	  if (document.cookie && document.cookie != '') {
	      var split = document.cookie.split(';');
	      for (var i = 0; i < split.length; i++) {
		  var name_value = split[i].split("=");
		  name_value[0] = name_value[0].replace(/^ /, '');
		  //alert(name_value[1]);
		  cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
	      }
	  }
	  
	  return cookies;
    }
};

//end jQuery.cookie---------------------------------------------------------------------------------------


$(document).ready(function() {
  
  if(window.location.pathname.split('/')[2]){window.scrollTo(0,128);}
  $('#header').click(function(){openhref('/'+$.cookie('lang')+'/');});
  
  var lang=$.cookie('lang');
  var email=$.cookie('email');
  if(email){
    $('#registration,#loginbox').hide(); 
    $('#edit-reg').html(email);
  }else{$('#edit-reg,#logout').hide();}


  $("#dim").css("height", $(window).height());
  $(".alert").click(function(){
	var action=$(this).attr('id');
	$.ajax({
	    url: '/ajax.php',
	    data: 'action='+action,
	    type: 'post',
	    success: function (data) {
		$("#msgbox-content").html(data);
		$("#dim").fadeIn(10);
	    }
	});
	return false;
  });

  $(".close").click(function(){
	$("#msgbox-content").html("");
	$("#dim").fadeOut(10);
	return false;
  });
  
  $('#logout').click(function(){
	$.cookie('email',null,{path: '/'});
	$.cookie('email',null,{path: '/'});
	$('#edit-reg,#logout').hide();
	$('#registration,#loginbox').show();
  });

  $('.login-form .submit').live('click',function(){
    var isValid = true;
    var email=$('.login-form input[name="email"]').val();
    var pass=$('.login-form input[name="pass"]').val();
    if(!isValidEmailAddress(email)) {isValid = false;}
    if(pass.length<2){isValid = false;}
    if(isValid){
      var data='email='+email+'&pass='+pass+'&action=login';
      $.ajax({
	url: '/ajax.php',
	data: data,
	type: 'post',
	dataType : 'json',
	success: function (response) {   
 	  if(response.error==0){
 	     $("#dim").fadeOut(10);
	     $('#edit-reg,#logout').show();
	     $('#registration,#loginbox').hide();
	     $('#edit-reg').html($.cookie('email'));
	     }else{$('div.msg').html(response.msg);}    
	}
      });
    }else{$('div.msg').html('error');}
  });
  
  $('.reg-form .submit').live('click',function(){
      var data='';
      var msg='<b>'+i18n[lang]['attention']+':</b><br />';
      var isValid = true;
      $(this).closest('form').find('input').each(function(){
	data += $(this).attr('name')+'='+ $(this).val() +'&';
	if($(this).hasClass('notempty')){
	  if($(this).val()==0){
	    $(this).addClass('notvalid');
	    isValid = false;
	  }else{$(this).removeClass('notvalid');}
	}
     });
     
     if(!isValid) msg+=i18n[lang]['fill_all_fields']+'<br />';
     var email = $(this).closest('form').find('input[name="email"]');
     var pass  = $(this).closest('form').find('input[name="pass"]');
     var re_pass = $(this).closest('form').find('input[name="re_pass"]');
     if(isValidEmailAddress(email.val())==false){
	email.addClass('notvalid');
	isValid = false;
	msg+=i18n[lang]['email_not_valid']+'<br />';
     }else{email.removeClass('notvalid');} 
     if(pass.val().length<5){
	isValid = false;
	msg+=i18n[lang]['min_pass']+'<br />';
	pass.addClass('notvalid');
	re_pass.addClass('notvalid');
     }
     if(pass.val()!=re_pass.val()){
	isValid = false;
	pass.addClass('notvalid');
	re_pass.addClass('notvalid');
	msg+=i18n[lang]['pass_not_ident'];
     }
     if(isValid){
	$.ajax({
	    url: '/ajax.php',
	    data: data+'action=newuser',
	    type: 'post',
	    dataType : 'json',
	    success: function (response) {
	      if(response.error==0){
		$('#msgbox-content').html(response.msg);
	      }else{
		$('div.msg').html(response.msg);
	      }    
	    }
	});
     }else{
	$('#msgbox').css('height','500px');
	$('div.msg').html(msg);
     }
     return false;
  });
  
  $(window).bind("resize", function(){$("#dim").css("height", $(window).height());});
  
  
  $('.leftmenu li ul').each(function(index) {
    $(this).hide();//Свертываем все узлы дерева
    $(this).prev().addClass('collapsible').click(function() {
      var this_i = $('ul.leftmenu ul').index($(this).next()); // The index of the submenu of the clicked link
      if ($(this).next().css('display') == 'none') { // Открытие списка
	// When opening one submenu, we hide all same level submenus:
	$(this).parent('li').parent('ul').find('ul').each(function(j) {
		if (j != this_i) {
			$(this).slideUp(200, function () {
				$(this).prev().removeClass('expanded').addClass('collapsed');
			});
		}
	});// :end
        $(this).next().slideDown(200, function () {
          $(this).prev().removeClass('collapsed').addClass('expanded');
        });
      }else {//Закрытие списка
        $(this).next().slideUp(200, function () {
          $(this).prev().removeClass('expanded').addClass('collapsed');
          $(this).find('ul').each(function() {
            $(this).hide().prev().removeClass('expanded').addClass('collapsed');
          });

        });
      }
      return true;
    });
  });
//------------------------------------------------------------------------------------------------------
   $('img[usemap]').maphilight({strokeColor: '519eb2'});
   
   $('#mailform').submit(function(){
       var email=$('#mailform .email').val();
       var mail_msg=$('#mailform textarea').val();
       if(mail_msg.length>1){
	$.ajax({
	  url: '/ajax.php',
	  data: 'action=mailform&msg='+mail_msg+'&email='+email,
	  type: 'post',
	  dataType: 'html',
	  success: function(html){
	    $('#mailform').replaceWith(html);
	  }
	});
       }
      return false;
   });
   
   $('.langico a').each(function(){
       var lang=$(this).parent().attr('class');
       if(lang==$.cookie('lang')){$(this).addClass('active');}
   });
  
    $('.langico a').click(function(){
      var lang=$(this).parent().attr('class');
      var cur_url=window.location.pathname;
      $.cookie('lang',lang,{path: '/'});
      $.ajax({
	      url: '/ajax.php',
	      data: 'action=chlang&lang='+lang+'&url='+cur_url,
	      type: 'post',
	      dataType : 'html',
	      success: function(new_url){openhref( new_url );}
      });
      return false;
    });

    $('.currency a').each(function(){
      var currency=$(this).find('span:not(.rate)').html();
      if(currency==$.cookie('currency')){$(this).addClass('active');}
      $(this).click(function(){
	  if(currency!=$.cookie('currency')){
	    $(this).closest('ul').find('a').removeClass('active');
	    $(this).addClass('active');
	    var rate=$(this).find('span.rate').html();
	    $.cookie('currency',currency,{path: '/'});
	    $.cookie('rate',rate,{path: '/'});
	    updateButtons();
	    cardSum();
	    if( window.location.href.indexOf('/card') + 1){updateCardCurrency();}
	    
	    if(window.location.href.search('/prod/') + 1){updateDetailCurrency();}
	  }
	  return false;
      });
    });


  updateButtons();
  cardSum();
  
  if(window.location.href.search('/prod/') + 1){updateDetailCurrency();}

  if( window.location.href.indexOf('/card') + 1){
    
    $('#card .quanity input').live('change',function(){
	var new_quanty=$(this).val();
	if(new_quanty>=0){
	    var id=$(this).closest('tr').attr('id').replace('prod','');
	    if(new_quanty>=1){
		var price=$(this).closest('tr').find('.price span.price-euro').html();
		var sum=new_quanty*price;
		$.cookie('prod'+id, new_quanty,{path: '/'});
		$.cookie('psum'+id, sum ,{path: '/'});
		$(this).closest('tr')
		  .animate({opacity: "0.1"}, "slow")
		  .animate({opacity: "1"}, "slow","linear",function(){cardReload();});
	    }else{
		$.cookie('prod'+id,null,{path: '/'});
		$.cookie('psum'+id,null,{path: '/'});   
		$(this).closest('tr').hide('slow',function(){cardReload();}); 
	    }
	}
    });
    
    $('#idpaypal').bind('submit',function(){
	    var isValid=true;
	    var order_data=$('#order_data');
	    var comment=$('textarea').val();
	    var email=order_data.find('input[name="email"]');
	    var post_type=$('input[type="radio"]').filter(':checked').val();
	    var userData='';
	    var msg;
	    
	    order_data.find('input[type="text"]').each(function(){
	      var userhash=$.cookie('user');
	      if(!userhash){ var userhash=0;}
    
	      var name=$(this).attr('name');
	      var val=$(this).val();    
	      userData+='&'+name+'='+val+'&userhash='+userhash;
	      if(($(this).hasClass('notempty'))&&(val.length<2)){
		$(this).addClass('notvalid');
		isValid = false;
	      }else{$(this).removeClass('notvalid');}	      
	    });

	    if(!isValidEmailAddress(email.val())){
	      isValid = false;
	      email.addClass('notvalid');
	    }else{
	      email.removeClass('notvalid');
	    }
	    
	    if((post_type=='post4')&&(comment.length<10)){
	      isValid = false;
	      $('textarea').addClass('notvalid');
	    }else{$('textarea').removeClass('notvalid');}
	   	    
	    if(isValid){
		var prod_table=$('#mailProd').html();
		var currency=$.cookie('currency');
		var total_sum=$('.total_sum').html();
		var subtotal_euro=$('.subtotal-e').html();
		var discount_sum_euro=$('.discount-e').html();
		var sendData='postType='+post_type+'&prodTable='+prod_table+'&subtotalEuro='+subtotal_euro+
			    '&discSumEuro='+discount_sum_euro+'&comment='+comment+'&currency='+currency
			    +'&total_sum='+total_sum+userData;
		var response_mail=false;	    
		$.ajax({
		    url: '/ajax.php',
		    data: 'action=orderSave&'+sendData,
		    type: 'post',
		    dataType : 'html',
		    async:false,   
		    success: function (response) {
		      if(response=='ok'){
			    response_mail=true;
			    $('#idpaypal input[name="amount"]').val(total_sum);
			    $('#idpaypal input[name="currency_code"]').val(currency);
 			    cleanCard();
			    return true;
		      }else{return false;}
		    }  
		});
//		if(response_mail){return true;}else{return false;}
	    }else{ 
	      alert('error:not valid'); 
	      return false; 
	    }


    });    
    
 
    
    $('#card input[type="radio"]').live('change',function(){updateCardCurrency();});
	
    updateCardCurrency();
  }
});
//------------------------------------------------------------------------------------------------------
function cardSum(){
    var allCookie=$.cookie();
    var csum=0;
    for(var i in allCookie) {
	if (!allCookie.hasOwnProperty(i)) continue;
	if(i.indexOf('psum')==0){
	  csum+=Number(allCookie[i]);
	}
    }
    $('.discount li').removeClass('active');
    if(csum>150){
      if(csum>300){
	if(csum>500){
	    $('#d1500').addClass('active');
	}else{$('#d1000').addClass('active');}
      }else{$('#d500').addClass('active');}
    }
    
    csum=csum*$.cookie('rate')
    $('#topmenu .price span.val').html(csum.toFixed(2));
    $('span#cur').removeClass().addClass($.cookie('currency'));
//$(this).find('.total span').removeClass().addClass($.cookie('currency'));
}

//------------------------------------------------------------------------------------------------------
function totalSum(t){//---------------------------------------------------------------------
      t.find('.total  p.val').html(function(){	  
  	 var b=t.closest('div.buttons');
	 var sum=b.find('input').val()*b.find('.price p.val').html();
	  if(sum<10000){
	    sum=sum.toFixed(2)
	  }else{
	    sum=sum.toFixed(0)
	  }
	  b.find('.total  p.val').html(sum);
      });
}//end totalSum()--------------------------------------------------------------------------


function updateButtons(){//--------------------------------------------------------------

  $('.buttons').each(function(){
    var price=Number($(this).find('.price span').html()*$.cookie('rate'));
    if(price<1000){price=price.toFixed(2);}else{price=price.toFixed(0);}
    $(this).find('.price p.val').html(price);

    var cook=$(this).attr('id');
    if($.cookie(cook)>0){
      $(this).find('.bay a').css('color','#fff');
      $(this).find('input').val($.cookie(cook));
    }

    $(this).find('.total span').removeClass().addClass($.cookie('currency'));
    $(this).find('a').unbind('click');
    totalSum($(this));
    $(this).find('.minus a').click(function(){
	 var b=$(this).closest('div.buttons');
	 var quanity = b.find('input').val();
  	 if(quanity>0){quanity=Number(quanity)-1;}else{quanity=0;}
	 b.find('input').val(quanity);
	 totalSum(b);
	 return false;
    });
    $(this).find('.plus  a').click(function(){
	 var b=$(this).closest('div.buttons');
	 var quanity = b.find('input').val();
  	 if(quanity>=0){quanity=Number(quanity)+1;}else{quanity=0;}
	 b.find('input').val(quanity);   
	 totalSum(b);
	 return false;
    });
    $(this).find('input').live("keyup",function(){
	 var b=$(this).closest('div.buttons');
	 totalSum(b);
    });
    $(this).find('.bay a').click(function(){
      var b=$(this).closest('div.buttons');
      var quanity = b.find('input').val();
      var sum = quanity * b.find('.price span').html();
      var id = b.attr('id').replace('prod','') ;
	if(quanity>=1){
	  $.cookie('prod'+id, quanity,{path: '/'});
	  $.cookie('psum'+id, sum ,{path: '/'});
	  $(this).css('color','#fff');
	}else{
	  $.cookie('prod'+id,null,{path: '/'});
	  $.cookie('psum'+id,null,{path: '/'});
	  $(this).css('color','#0e4d75');
	}
       b.closest('.goodsbox,.detailbox').animate({opacity: "0.4"}, "slow").animate({opacity: "1"}, "slow");
      cardSum();
    });

  });
}//end updateButtons(currency)--------------------------------------------------------------

function cardReload(){
  $.ajax({
	url: '/ajax.php',
	data: 'action=cardreload',
	type: 'post',
	dataType : 'html',
	success: function (response) {
	  $('#card').replaceWith(response);
	  updateCardCurrency();
	}   
  });
}

function cleanCard(){
  var allCookie=$.cookie();
  for(var i in allCookie) {
    if (!allCookie.hasOwnProperty(i)) continue;
    if((i.indexOf('psum')==0)||(i.indexOf('prod')==0)){
      $.cookie(i,null,{path: '/'});
    }
  }
}

function updateCardCurrency(){
  var rate=$.cookie('rate');
  var currency=$.cookie('currency');
  var post_price=parseFloat($(':radio[name=post]').filter(':checked').next('span').html());
  var discount_sum=$('.discount-e').html()*rate;
  var subtotal=$('.subtotal-e').html();
  var total=post_price+discount_sum;
  
  $('.curr-avatar').removeClass().addClass('curr-avatar '+currency);
  $('.subtotal-e').next().html(moneyRound(subtotal*rate,true));
  $('.discount-e').next().html(moneyRound(discount_sum,true));
  $('.total_sum').html(moneyRound(total,true));
  $('#card tr').each(function(){
    var pItem=$(this);
    var price=pItem.find('.price-euro').html();
    var total_price=pItem.find('.total-price-euro').html();
    pItem.find('.price .val').html(moneyRound(price*rate,true));
    pItem.find('.total_price .val').html(moneyRound(total_price*rate,true));
  });
}

function updateDetailCurrency(){
    var rate=$.cookie('rate');
    var currency=$.cookie('currency');
    
    $('.curr-avatar').removeClass().addClass('curr-avatar '+currency);
    var price_eur=$('span.price').html();
    $('span.price').next('b').html(moneyRound(price_eur*rate,true));
}

function isValidEmailAddress(emailAddress) {
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(emailAddress);
}

function moneyRound(amount,cent){
  if(cent){
    var result=(Math.round(amount*100))/100;
  }else{
    var result=Math.round(amount);
  }
  return result; 
}

function openhref( link ){
  var isMSIE = /*@cc_on!@*/false;
  if( isMSIE ) window.location.href( link );
  else window.location.href = link;
}
