$.tabs = function(selector, start) {$(selector).each(function(i, element) {$($(element).attr('rel')).css('display', 'none');$(element).click(function() {$(selector).each(function(i, element) {$(element).removeClass('selected');$($(element).attr('rel')).css('display', 'none');});$(this).addClass('selected');$($(this).attr('rel')).css('display', 'block');});});if (!start) {start = $(selector + ':first').attr('rel');} $(selector + '[rel=\'' + start + '\']').trigger('click');};

//// Json Constants Array

var JSonData = ConstJS.constants;

//// Validate Functions

function checkname()
	{var str=document.getElementById('first_name').value;
	 var filter=/^[А-ЯA-Z-]{2,}( +)?([А-ЯA-Z]{2,})?( +)?$/i;
	 if (filter.test(str)) {document.getElementById('name_div').style.visibility="hidden"; document.getElementById('name_pic').style.visibility="visible";} else {document.getElementById('name_pic').style.visibility="hidden"; document.getElementById('name_div').style.visibility="visible";}
	}
function checksurname()
	{var str=document.getElementById('last_name').value;
	 var filter=/^[-А-ЯA-Z]{2,}( +)?([А-ЯA-Z]{2,})?( +)?$/i;
	 if (filter.test(str)) {document.getElementById('surname_div').style.visibility="hidden"; document.getElementById('surname_pic').style.visibility="visible";} else {document.getElementById('surname_pic').style.visibility="hidden"; document.getElementById('surname_div').style.visibility="visible";}}
function checkmail()
	{var str=document.getElementById('email').value;
	 var filter=/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/;
	 if (filter.test(str)) {document.getElementById('mail_div').style.visibility="hidden"; document.getElementById('mail_pic').style.visibility="visible";} else {document.getElementById('mail_pic').style.visibility="hidden"; document.getElementById('mail_div').style.visibility="visible";}
	}
function checkphone()
	{var str=document.getElementById('phone').value;
	 var filter=/^(?:8|\+7)? ?\(\d{1,5}\)? ?\d{1,5}\-\d{2}\-\d{2}$/;
	 if (str != "") {document.getElementById('phone_div').style.visibility="hidden"; document.getElementById('phone_pic').style.visibility="visible";} else {document.getElementById('phone_pic').style.visibility="hidden"; document.getElementById('phone_div').style.visibility="visible";}
	}
 
function open_window(link,w,h) //opens new window
	{
	var win = "width="+w+",height="+h+",menubar=no,location=no,resizable=yes,scrollbars=yes";
	newWin = window.open(link,'newWin',win);
	newWin.focus();
	}

function validate_custinfo() //validate customer information
	{	
	
	var strFName=document.getElementById('first_name').value;
	var filterFName=/^[А-ЯA-Z]{2,}( +)?([А-ЯA-Z]{2,})?( +)?$/i;

	if (!filterFName.test(strFName)) 
		{
		alert(JSonData.ERROR_INPUT_NAME);
		return false;
		}

	var strSName=document.getElementById('last_name').value;
	var filterSName=/^[А-ЯA-Z]{2,}( +)?([А-ЯA-Z]{2,})?( +)?$/i;

	if (!filterSName.test(strSName)) 
		{
		alert(JSonData.ERROR_INPUT_NAME);
		return false;
		}

	var strEmail=document.getElementById('email').value;
	var filterEmail=/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/;

	if (!filterEmail.test(strEmail)) 
		{
		alert(JSonData.ERROR_INPUT_EMAIL);
		return false;
		}

	var strPhone=document.getElementById('phone').value;
	var filterPhone=/^(?:8|\+7)? ?\(\d{1,5}\)? ?\d{1,5}\-\d{2}\-\d{2}$/;
	if (str ="" )
		{
		alert(JSonData.ERROR_INPUT_PHONE);
		return false;
		}
	return true;
	}

//// Payment functions

function checkSubmit() {
	if (document.getElementById("idto").value != "") return true;
	else 
	  {
		alert("Введите номер телефона в формате 9059103456");
		return false;
	  }
	}

//// Mode Functions

function moduleSearch()
	{location = "./index.php?searchstring="+$('#mod_search_searchword').attr('value');}

function cart_update(form)
{
  var array_input = document.getElementsByTagName('input');
  
  for (var i=0; i<array_input.length; i++)
  {
     if ((array_input[i].name.split('_')[1])=='instock') 
     {
        id=array_input[i].name.split('_')[2];
        if ((Math.round(array_input[i].value*100)/100) <(Math.round(document.getElementById('count_'+id).value*100)/100))
        {
          alert('Перевышено максимально возможное количество для '+document.getElementById('name'+id).innerHTML); return false;
 
        }
     }
  } 
  form="#"+form;
  $(form).submit();
}

function currencyFormat(num, dec) {
  num = Math.round( num / dec ) * dec;
  num = new Number(num).toFixed(2);   // особенности счета JavaScript ( x/100 не всегда = x*0.01 )
  var s = 0;
  var str = '';
  for( var i=num.toString().length-1; i>=0; i-- ) {
    s++;
    str = num.toString().charAt(i) + str;
    if(num.toString().charAt(i)=='.') s=0;
    if( s > 0 && !(s % 3) ) str  = " " + str;
  } 
  return str;         
}

function googleTranslateElementInit()
	{
	new google.translate.TranslateElement(
		{pageLanguage: json_const.PAGE_LANG,includedLanguages: 'en, ru'}, 'google_translate_element');
	}


if(document.getElementsByClassName) {
	 
	    getElementsByClass = function(classList, node) {   
	        return (node || document).getElementsByClassName(classList)
	    }
	 
	} else {
	 
	    getElementsByClass = function(classList, node) {           
	        var node = node || document,
	        list = node.getElementsByTagName('*'),
	        length = list.length, 
	        classArray = classList.split(/\s+/),
	        classes = classArray.length,
	        result = [], i,j
	        for(i = 0; i < length; i++) {
	            for(j = 0; j < classes; j++)  {
	                if(list[i].className.search('\\b' + classArray[j] + '\\b') != -1) {
	                    result.push(list[i])
	                    break
	                }
	            }
	        }
	     
	        return result
	    }
	}







$(document).ready(function(){   

// Ajax cart function
    $('.ajaxcart').click(function () {                //Биндим клик по классу ajxcart
        var curid = this.id.split('_')[1];            //Смотрим id (вида tocard_123) и берем из него код продукта
        var option = ''; 
        var table = document.getElementById('products'); 
        var new_priceid="newprice"+curid; 
        var countp='count_'+curid;
        if (document.getElementById(countp)) $kol=document.getElementById(countp).value;
        else $kol=1;
        var new_price = document.getElementById(new_priceid).value; 
        var array_options = document.getElementsByTagName('select');
        if (new_price) new_price=new_price.replace(' ',''); else new_price='';
  
        for (var oi=0; oi<array_options.length; oi++)
        {
             if ((array_options[oi].name.split('_')[2])==curid) 
             { 
              if (oi==0)
              option= array_options[oi].name.split('_')[3] +':'+array_options[oi].value.split(':')[0];
              else option= option +',' + array_options[oi].name.split('_')[3] +':'+array_options[oi].value.split(':')[0];
             }  
            
        }
        
        poststr = "shopping_cart=yes&add2cart=" + curid + "&type=ajax&kol="+$kol+"&opt="+option+"&newprice="+new_price;        //Формируем POST
        $.ajax(                            //Отправляем
        {
            type: "GET",
            url: "./includes/shopping_cart.php",
            data: poststr,
            success:
                function (response)				   //Обрабатываем ответ
                    {

                        if (response==-1) {alert('Перевышено максимально возможное количество данного товара'); return false;}
			var return_data = eval("("+response+")");  //JSON.parse();

                        $('#sci').text(return_data.info.count);    //Пишем количество товаров в элемент с id="sci"
                        $('#scs').text(return_data.info.cost);     //Пишем сумму товаров в элемент с id="scs"
            //Тут же функции анимации и прочих красивостей

				var image = $('#dp'+curid).offset();
				var cart  = $('#module_cart').offset();
	
				$('#dp'+curid).before('<img src="' + $('#dp'+curid).attr('src') + '" id="temp" style="position: absolute; top: ' + image.top + 'px; left: ' + image.left + 'px;" />');
	
				params = {
					top : cart.top + 'px',
					left : cart.left + 'px',
					opacity : 0.0,
					width : $('#module_cart').width(),  
					heigth : $('#module_cart').height()
				};		
	
				$('#temp').animate(params, 'slow', false, function () {
					$('#temp').remove();
				});
                    }
        });
	return false;
    });

// Jcarusel hits show
    $(".carouselDiv .jCarouselLite").jCarouselLite({auto: JSonData.CONF_HITS_FRIQ, speed: JSonData.CONF_HITS_SPEED, vertical: true, visible: JSonData.CONF_SCROLL_HITS, easing: "easeinout"});

// HideSlide hits show
    var fadeTime = 2000*(JSonData.CONF_HITS_FRIQ/10000);var i = $('.slide').length;var x = 0;showSlide();function showSlide(){curSlide = "#slide" + x;if(x == 0){prevSlide = "#slide" + (i - 1);} else {prevSlide = "#slide" + (x - 1);}$(prevSlide).fadeOut(fadeTime, function(){$(curSlide).fadeIn(fadeTime);if(x == (i - 1)){x = 0;} else {x++;}});setTimeout(showSlide, JSonData.CONF_HITS_FRIQ);}

// Tabs

    if (JSonData.REVIEW_SAVED != 1) {$.tabs('.tabs a');} else {$.tabs('.tabs a', '#tab_review');}

// Search
    $('#mod_search_searchword').keydown(function(e) {if (e.keyCode == 13) {moduleSearch();}});

// Tag flash cloud
      if (document.getElementById('tag'))  
      { 
	    var rnumber = Math.floor(Math.random()*9999999);
	    var so = new SWFObject("./core/tagcloud.swf?r="+rnumber, "tagcloudflash", "160", "160", "5", "#ffffff");
	    so.addParam("allowScriptAccess", "always");
	    so.addParam("wmode", "transparent");
	    so.addVariable("tcolor", "0x5e0b6e");
	    so.addVariable("tspeed", "150");
	    so.addVariable("distr", "true");
	    so.addVariable("mode", "tags");
	    so.addVariable("tagcloud", JSonData.TAGS_CLOUD);
	    so.write("wpcumuluscontent");
     }
});

$(document).ready(function() {
    $("a.thickbox").fancybox();


$("a#iframe").fancybox({
                    'type' : 'iframe',
                    'overlayShow': 'TRUE',
                    'hideOnOverlayClick': 'FALSE',
                    'height': 900,
                    'width': 1100       
	            
	           });     




    $("a[rel=example_group]").fancybox({
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'titlePosition' 	: 'over',
				'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
					return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
				}
			});
    $("a[rel=example_group1]").fancybox({
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'titlePosition' 	: 'over',
				'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
					return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
				}
			}); 

});

//Pool
$(document).ready(function(){
  $("#poll").submit(formProcess); // setup the submit handler
  
  if ($("#poll-results").length > 0 ) {
    animateResults();
  }
  if (document.getElementById('idvote')) 
  {
   idvote=document.getElementById('idvote').value;
  }   
  if ($.cookie('vote_id_'+idvote)) {
    $("#poll-container").empty();
    votedID = $.cookie('vote_id_'+idvote);
    $.getJSON("poll.php?vote=none",loadResults);
  }
});

function formProcess(event){
  event.preventDefault();
  
  var id = $("input[@name='poll']:checked").attr("value");
  id = id.replace("opt",'');
  idvote=document.getElementById('idvote').value;
  $("#poll-container").fadeOut("slow",function(){
    $(this).empty();
    
    votedID = id;
    $.getJSON("poll.php?vote="+id+'&idvote='+idvote,loadResults);
    
    $.cookie('vote_id_'+idvote, id, {expires: 365, path: '/'});
    });
}

function animateResults(){
  $("#poll-results div").each(function(){
      var percentage = $(this).next().text();
      $(this).css({width: "0%"}).animate({
				width: percentage}, 'slow');
  });
}

function loadResults(data) {
  var total_votes = 0;
  var percent;
  
  for (id in data) {
    total_votes = total_votes+parseInt(data[id][OPT_VOTES]);
  }
  
  var results_html = "<div id='poll-results'>\n<dl class='graph'>\n";
  for (id in data) {
    percent=0; 
    if (data[id][OPT_VOTES]>0) 
      percent = Math.round((parseInt(data[id][OPT_VOTES])/parseInt(total_votes))*100);
    if (data[id][OPT_ID] !== votedID) {
      results_html = results_html+"<dd  style='float:left;' class='bar-container'><div id='bar"+data[id][OPT_ID]+"'style='width:0%; float:left; '><nobr><b>"+data[id][OPT_TITLE]+"</b></nobr></div><strong>"+percent+"%</strong></dd>\n";
    } else {
      results_html = results_html+"<dd class='bar-container' style='float:left;'><div id='bar"+data[id][OPT_ID]+"'style='width:0%;background-color:#eec4ea; float:left;'><nobr><b>"+data[id][OPT_TITLE]+"</b></nobr></div><strong>"+percent+"%</strong></dd>\n";
    }
  }
  
  results_html = results_html+"</dl><p style='clear: both;'>Всего голосов: "+total_votes+"</p></div>\n";
  
  $("#poll-container").append(results_html).fadeIn("slow",function(){
    animateResults();});
}
