$(document).ready(function(){
  var elem = $(window);
  var contentTD = 0;
  $("div.rate").css({backgroundPosition: "-42px 0"});
  $("#s-move").css( {'margin-left' : '0px' } );
  $("#s-right").css( {backgroundPosition: "0px -45px"} );
  $("#s-left").css( {backgroundPosition: "0px -45px "} );
//----
    $("A").mousedown( function(){  
         $(this).blur();
    }).focus( function(){
         $(this).blur();
    }).click( function(){
         $(this).blur();
    });
//----
    $("div.rate").mouseover(function(e){
       $(this).animate({backgroundPosition:"(0px 0px)"}, {duration:500});
       $("#float-container").append('<div id="float-text"><div id="shadow"><div>'+$(this).attr("name")+'</div></div></div>');
       $("#shadow").dropShadow({left: 5, top: 5, opacity: 0.2, blur: 0});
       $("#float-text").css( {'position':'absolute','top': e.pageY,'left':e.pageX,'z-index':'200' } );
    }).mouseout(function(e){
       $(this).animate({backgroundPosition:"(-42px 0px)"}, {duration:500});
       $("div#float-text").remove();
    }).mousemove(function(e){
       $("#float-text").css( {'position':'absolute','top': e.pageY,'left':e.pageX,'z-index':'200' } );
    }).click(function(){
       window.location.href = $(this).attr("link");
    });

//----
    $("div.buy-block").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -43px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.quest-block").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -43px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.find-block").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -28px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.f-3").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -125px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.f-2").click(function(){
	window.location.href = "/basket/";
    }).mouseover(function(){
        $(this).css( {backgroundPosition: "0px -122px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.s-2").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -200px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.s-1").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -200px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });

    $("div.s-3").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -200px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });

    $("div.submit").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -29px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $("div.refresh").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -29px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
//----
    $("div.news-text").mouseover(function(){
        $(this).css( {color: "#fff"} );
    }).mouseout(function(){
        $(this).css( {color: "#ddd"} );
    });
//----
    $("a.icon").mouseover( function() {
	var id  = parseInt($(this).attr("id").replace( /aicon/g,"" ));
	var text = $(this).attr("text");
	$("#cicon" + id).css({ 'width' : '80px','height' : '80px'});
	$("#icon" + id).css({ 'width' : '80px','height' : '80px'});
	$("#text" + id).css({ 'display' : 'block'});

	//$("#icon" + (id-1)).css({ 'width' : '60px','height' : '60px'});
	//$("#icon" + (id+1)).css({ 'width' : '60px','height' : '60px'});	
    }).mouseout(function(){
	// $.each( $("a.icon"), function() {
		var id  = $(this).attr("id").replace( /aicon/g,"" );
		$("#cicon" + id).css({ 'width' : '40px','height' : '40px'});
	 	$("#icon" + id).css({ 'width' : '40px','height' : '40px'});	
		$("#text" + id).css({ 'display' : 'none'});
	// });
    }).click(function(){
       // history.back();
    });
    $("div.btn-refresh").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -31px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    }).click(function(){
        window.location.href="/gift/";
    });	
//----    
    $("div.cat-item").mouseover(function(){
	 $(".cat-menu").css({ 'visibility' : 'hidden' });
        var popid = $(this).attr("id").replace("cat-item","");
        var popX = ( 836/6 ) * ( popid - 1 );
        if( popX > 636 ) popX = 636;
	 popY = ( window.location == "http://www.optistore.ru/" ) ? '423px' : '129px';
	 $("#cat-menu" + popid).css({ 'visibility' : 'visible', 'top' : popY, 'left' : popX });
	 popstatus[popid] = 1;
    }).mouseout(function(){
        var popid = $(this).attr("id").replace("cat-item","");
	 popstatus[popid] = 0;
	 setTimeout( "removemenu()", 300 );
    });

    $("div.cat-menu").mouseover(function(){
	 $(".cat-menu").css({ 'visibility' : 'hidden' });
        var popid = $(this).attr("id").replace("cat-menu","");
        var popX = ( 836/6 ) * ( popid - 1 );
        if( popX > 636 ) popX = 636;
	 popY = ( window.location == "http://www.optistore.ru/" ) ? '423px' : '129px';
	 $("#cat-menu" + popid).css({ 'visibility' : 'visible', 'top' : popY, 'left' : popX });
	 popstatus[popid] = 1;
    }).mouseout(function(){
        var popid = $(this).attr("id").replace("cat-menu","");
	 popstatus[popid] = 0;
	 setTimeout( "removemenu()", 300 );
    });

 //----

  $("#s-right").mousedown(function(e) {
  	paneScroll( 3, 130, 7 );
  	$("#s-right").css( {backgroundPosition: "0px -1px"} );
  }).mouseup(function(e) {
  	$("#s-right").css( {backgroundPosition: "0px -45px"} );
	paneScrollKill();
  });
  $("#s-left").mousedown(function(e) {
  	paneScroll( -3, 130, 7 );
  	$("#s-left").css( {backgroundPosition: "0px -1px"} );
  }).mouseup(function(e) {
	paneScrollKill();
  	$("#s-left").css( {backgroundPosition: "0px -45px"} );
  });
	 
 //---
    $("a.float-link").mouseover(function(e){
       $("#float-container").append('<div id="float-text"><div id="shadow"><div>'+$(this).attr("anons")+'</div></div></div>');
       $("#shadow").dropShadow({left: 5, top: 5, opacity: 0.2, blur: 0});
       var floatX = ( elem.width() < e.pageX + 320 ) ? e.pageX - 320 : e.pageX+20;
       var floatY = ( elem.height() < e.pageY + 320 ) ? e.pageY - 320 : e.pageY;
       $("#float-text").css( {'position':'absolute','top': floatY,'left':floatX,'z-index':'200' } );
    }).mouseout(function(){
       $("div#float-text").remove();
    }).mousemove(function(e){
       var floatX = ( elem.width() < e.pageX + 320 ) ? e.pageX - 320 : e.pageX+20;
       var floatY = ( elem.height() < e.pageY + 320 ) ? e.pageY - 320 : e.pageY;
       $("#float-text").css( {'position':'absolute','top': floatY,'left':floatX,'z-index':'200' } );
    })
//----
	var toUseSearch = 0;
	$("#searchfld").focus(function () {
		toUseSearch = "searchfld";
		$("#searchfld").val("");	
	});
	$("#searchfld").blur(function () {
		toUseSearch = 0;
		if( $("#searchfld").val() == "" ) $("#searchfld").val("поиск..");	
	});
	$("#searchfld1").focus(function () {
		toUseSearch = "searchfld1";
	});
	$("#searchfld1").blur(function () {
		toUseSearch = 0;
	});
	$("#sbutton1").click(function () {
		search("searchfld1");
	});
	$("#sbutton").click(function () {
		search("searchfld");
	});
	$(document).keyup(function(e) {
		if (e.keyCode == 13 && toUseSearch != 0 ) {
			search( toUseSearch );
		}
	});

//----
	$(".bm-link").click(function() {
		$(".bm-area").css( {'display':'none'} );
	    $(".bm-active").attr( "class", "bm-link" );
		$(this).attr( "class", "bm-active" ); 
		var bmactive = $(this).attr("bm"); 
		$("#bm" + bmactive).css( {'display':'block'} );
		$(".bm-bg-i").css( {'backgroundImage':'url(/project/img/bm-non.gif)'} );
		$("#bm-bg" + bmactive).css( {'backgroundImage':'url(/project/img/bm-act.gif)'} );
	});
//----
	$(".curselect").change(function() {	
		makePrice( $(".curselect option:selected").val() );	
	});

//----
	$("#service-call").click(function() {
		alert("Функция в разработке");
	});
	$("#service-online").click(function() {
		alert("Функция в разработке");
	});
	$("#service-mail").click(function() {
		alert("Функция в разработке");
	});
//----
  $( ".pop" ).mouseover( function() {
     var pid = parseInt( $(this).attr("pop") ) - 1;
     $(".popmenu").css({ 'left' : '-500px' });
     var openPopX = ( elem.width() - 982 )/2  + parseInt( $(this).attr("left") );
     $("#popid" + pid).css( { 'left' : openPopX } );
  });
});


var scroll_width = 0;
var scroll_id = 0;
function paneScroll( step, width, forpage ) {
	var wi = parseInt( $('#s-move').css('width') );
	var max_id = Math.floor( wi / width ) - forpage;
	var min_id = 0;
	scroll_id += step;
	if( scroll_id < 0 ) 		scroll_id = 0;
	if( scroll_id > max_id ) 	scroll_id = max_id;

    	var $paneOptions = $('#s-container');
	$('#test').html( (scroll_id+1) + "-" + (scroll_id+forpage) + " ?? " + ( max_id + forpage ) );

	$paneOptions.stop().scrollTo( { top: 0, left: ( scroll_id * width ) } , 1000 ); //alert( scroll_id * width );
	scrollid = setTimeout( "paneScroll( " + step + "," + width + "," + forpage  + " )", 1000);
}
function paneScrollKill( ) {
	clearTimeout( scrollid );
}


function showRating( max, rating ) {
  $.each(rating, function(i, val) {
    var rateHeight = parseInt(val/max*120)+10;
    $("#rate"+(rating.length-i)).animate({ height: rateHeight }, 1500 );
  });
}



function removemenu( ) {
     $(".popmenu").css({ 'left' : '-500px' });
}

function search( toUseSearch ) {
	var addurl = "";
       var s = document.getElementById(toUseSearch ).value;
	s = s.replace("(", "");
	s = s.replace(")", "");

	s = encodeURIComponent(s);
	s = s.replace(/%20/g, "+");
	if( s != '') {
		var url = "/searchtext/search," + s + "/" + addurl;
		window.location.href = url;
	}
    return false;
}

function getElements(tag, name) {
     
     var elem = document.getElementsByTagName(tag);
     var arr = new Array();
     for(i = 0,iarr = 0; i < elem.length; i++) {
          att = elem[i].getAttribute("class");
          if(att == name) {
               arr[iarr] = elem[i];
               iarr++;
          }
     }
     return arr;
}

function makePrice( index ) {
	var price = new Array();
	var curs = new Array( " Руб", " EUR", " USD" );
	var p = getElements("input", "pricetrue"); 
	for(i=0; i<p.length;i++) {
		price[i] = p[i].value * currents[0]; // заменить если валюта другая по умолчанию - должна быть цена в рублях
	}
	var p = getElements("div", "price");
	for(i=0; i<p.length;i++) {
		p[i].innerHTML = ((100*price[i]/currents[index])/100).toFixed(2) + "" + curs[index] ;
	}
}


function SetOrder( id , param, price) {

	var count = parseInt( $('#count' + id).val() );
	if( !count ) count = 1;
	var sum = parseInt( $('#sumtrue').val() );
	var sum = parseFloat( sum );

	if( param == 0) {
	    	var xy = getScrollXY();
   		var elem = $(window);
    		var floatX = ( elem.width() - 354 ) / 2;
    		var floatY =  (elem.height() / 2 - 50) + xy[1] ;
		$("#body").append("<div class=\"float-alert\" id=\"float-alert\"><p>Вы действительно хотите удалить позицию из корзины?</p><div class=\"inner\" style=\"width: 190px;\"><div class=\"rol-ok\"><a href=\"javascript:;\"><img src=\"/project/img/pixel.gif\" width=91 height=28></a></div><div class=\"rol-cancel\"><a href=\"javascript:;\"><img src=\"/project/img/pixel.gif\" width=91 height=28></a></div></div></div>");
		$("#float-alert").css( { 'top': floatY, 'left': floatX, 'visibility' : 'visible' } );
    		$("div.rol-ok").mouseover(function(){
       		$(this).css( {backgroundPosition: "0px -29px"} );
   		}).mouseout(function(){
        		$(this).css( {backgroundPosition: "0px 0px"} );
   		}).click(function(){
 			$('#orderid' + id).css({'display':'none'});
			$('#sum').html( sumBetter( sum - count * price) ); 
 			closeAlert(); 
			$.get("/project/phpfiles/_ajax.php", { id: id, action: 'order', param: param, count: count, price: price }, function(data) {
				$("#basket").html( data );
			});     		
    		});
    		$("div.rol-cancel").mouseover(function(){
       		$(this).css( {backgroundPosition: "0px -29px"} );
   		}).mouseout(function(){
        		$(this).css( {backgroundPosition: "0px 0px"} );
   		}).click(function(){
 			closeAlert();
			return;      		
    		});
		return;
	} else {
		if( param == 2) {
			$('#sum').html( sumBetter( sum + count * price - parseFloat($('#sum' + id).html())));
			$('#sum' + id).html( (count * price).toFixed(0) );
		} else {
	    		var xy = getScrollXY();
   			var elem = $(window);
    			var floatX = ( elem.width() - 354 ) / 2;
    			var floatY =  (elem.height() / 2 - 50) + xy[1] ;
			$("#body").append("<div class=\"float-alert\" id=\"float-alert\"><p>В корзину добавлено элементов: " + count + "</p><div class=\"inner\"><div class=\"rol-ok\"><a href=\"javascript:;\" onclick=\"closeAlert();\"><img src=\"/project/img/pixel.gif\" width=91 height=28></a></div></div></div>");
			$("#float-alert").css( { 'top': floatY, 'left': floatX, 'visibility' : 'visible' } );
    			$("div.rol-ok").mouseover(function(){
       			 $(this).css( {backgroundPosition: "0px -29px"} );
   			 }).mouseout(function(){
        			$(this).css( {backgroundPosition: "0px 0px"} );
    			});
		}
	}
	$.get("/project/phpfiles/_ajax.php", { id: id, action: 'order', param: param, count: count, price: price }, function(data) {
		$("#basket").html( data );
	});
}



function closeAlert() {
	$("#float-alert").remove();
}

function sumBetter (sum) {
	sum = sum.toFixed(2);
	$('#sumtrue').val( sum );
	sum = sum.toString(); 
	drob = sum.split(".");
	n = drob[0].length; 
	newSum = "";
	for( i=3; i <= n+3; i +=3 ) {
		newSum = drob[0].substring(n-i, n-i+3) + " " + newSum ;
	}
	return newSum;// + "." + drob[1];
}


function floatProgress() {
    $("#form-progress").html( "Отправляем сообщение.. Пожалуйста, подождите..." );
}

function openFloatForm( id, name ) {
    var xy = getScrollXY();
    var elem = $(window);
    var floatX = ( elem.width() - 350 ) / 2;
    var floatY =  (elem.height() / 2 - 200) + xy[1] ;
    $("#form-header").html( name );
    $("#tovarname").val( name );
    $("#form-question").css( {'position':'absolute','top': floatY,'left':floatX,'z-index':'200' } );
    $("#form-shadow").dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
    $("#form-question").css({'visibility':'visible'});
}

function closeFloatForm( id ) {
    $("#form-progress").html(" ");
    $("#form-" + id ).css({'visibility':'hidden'});
}

function getScrollXY() {
       var scrOfX = 0, scrOfY = 0;
       if( typeof( window.pageYOffset ) == 'number' ) {
               //Netscape compliant
               scrOfY = window.pageYOffset;
               scrOfX = window.pageXOffset;
       } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
               //DOM compliant
               scrOfY = document.body.scrollTop;
               scrOfX = document.body.scrollLeft;
       } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
               //IE6 Strict
               scrOfY = document.documentElement.scrollTop;
               scrOfX = document.documentElement.scrollLeft;
       }
       return [ scrOfX, scrOfY ];
}

function fixPNG(element, type)
{
  //???? ??????? IE ?????? 5.5-6
  if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
  {
    var src;
    if (element.tagName=='IMG') //???? ??????? ??????? ???????? (??? IMG)
    {
      if (/\.png$/.test(element.src)) //???? ???? ???????? ????? ?????????? PNG
      {
        src = element.src;
        element.src = "/_img/serv/1x1.gif"; //???????? ??????????? ?????????? gif-??
      }
    }
    else //?????, ???? ??? ?? ???????? ? ?????? ???????
    {
	  //???? ? ???????? ?????? ??????? ????????, ?? ??????????? ???????? ???????? background-?mage ?????????? src
      src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
      if (src)
      {
        src = src[1]; //????? ?? ???????? ???????? background-?mage ?????? ????? ????????
        element.runtimeStyle.backgroundImage="none"; //??????? ??????? ???????????
      }
    }
    //????, src ?? ????, ?? ????? ????????? ??????????? ? ??????? ??????? AlphaImageLoader
	type = (type == 1) ? "crop" : "scale";

  if (src) element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='"+type+"')";
  }
}


