var popstatus = new Array(0,0,0,0,0,0,0);

$(document).ready(function(){
  var elem = $(window);
	scanOpenSessions();

	$(".bm-bg-i").css( {'backgroundImage':'url(/project/img/bm-non.gif)'} );
	//$("#bm-bg1").css( {'backgroundImage':'url(/project/img/bm-active.gif)'} );

	$.fn.tagName = function() { 
		return this.get(0).tagName; 
	} 
	$.fn.maxZIndex = function(opt) {
		var def = { inc: 10, group: "*" };
		$.extend(def, opt);    
		var zmax = 0;
		$(def.group).each(function() {
			var cur = parseInt($(this).css('z-index'));
			zmax = cur > zmax ? cur : zmax;
		});
		if (!this.jquery)
			return zmax;

		return this.each(function() {
			zmax += def.inc;
			$(this).css("z-index", zmax);
		});
	}
	$.extend($.expr[':'], {  
		noid: function(a) {  
			return $(a).attr("id") == '';  
		}  
	}); 

//----
    $("A").mousedown( function(){  
         $(this).blur();
    }).focus( function(){
         $(this).blur();
    }).click( function(){
         $(this).blur();
    });

//----
    $("div.buy-block").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -16px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
    $(".quest-block").mouseover(function(){
        $(this).css( {backgroundPosition: "0px -16px"} );
    }).mouseout(function(){
        $(this).css( {backgroundPosition: "0px 0px"} );
    });
	
/**
 *  Переключение между отправкой запроса по товару		
 *  и конфигуратором серверов
 */
    $(".switch").click(function() {
	// delete shadow from container
    	var sid = $("#form-shadow").shadowId();
    	$("#"+sid).remove();
	
	if( $("#form-shadow").css('width') == '700px' ) {
		var options = ['block', 'none', 550, 300 ]; // quest vis, conf vis, window width, window height
	} else {
		var options = ['none', 'block', 700, 500 ];
	}

	// show & hide form blocks: conf <-> quest
	$("#table-quest").css('display', options[0] );	
	$("#table-conf").css('display', options[1] );	

	// animate window
	var xy = getScrollXY();	
	var newLeft = ( elem.width() - options[2] )/2;
    	var newTop =  ( elem.height() - options[3]  )/2 + xy[1] ;
	$("#form-shadow").animate({ 'width': options[2]+'px', 'height': options[3]+'px', 'top': newTop+'px', 'left': newLeft+'px' }, 700, function() {
    		$("#form-shadow").dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});			
	});
    });

    $("#form-shadow select").change( function() {
	var confString = "";
       $.each( $("#form-shadow option:selected"), function() {
		if( $(this).val() != "---" ) confString += $(this).val() + "\n";
	});
	$(".question").val( confString );
    });
     

//----
    $("div.cat-item").mouseover(function(){
	 var bgShift = 0;
	 $(".cat-menu").css({ 'visibility' : 'hidden' });
        var popid = $(this).attr("id").replace("cat-item","");
        var popX = ( 1004/6 ) * ( popid - 1 );
        if( popX > 800 ) {
		popX = 805;
		bgShift = '30px';
	 }
	 popY = '98px'; //( window.location == "http://www.optistore.ru/" ) ? '423px' : '98px';
	 $("#cat-menu" + popid).css({ 'visibility' : 'visible', 'top' : popY, 'left' : popX, 'backgroundPosition' : bgShift + ' 0' });
	 popstatus[popid] = 1;
    }).mouseout(function(){
        var popid = $(this).attr("id").replace("cat-item","");
	 popstatus[popid] = 0;
	 setTimeout( "removemenu()", 300 );
    });
//----
    $("div.cat-menu").mouseover(function(){
	 var bgShift = 0;
	 $(".cat-menu").css({ 'visibility' : 'hidden' });
        var popid = $(this).attr("id").replace("cat-menu","");
        var popX = ( 1004/6 ) * ( popid - 1 );
        if( popX > 800 ) {
		popX = 805;
		bgShift = '30px';
	 }
	 popY = '98px';//( window.location == "http://www.optistore.ru/" ) ? '423px' : '98px';
	 $("#cat-menu" + popid).css({ 'visibility' : 'visible', 'top' : popY, 'left' : popX, 'backgroundPosition' : bgShift + ' 0' });
	 popstatus[popid] = 1;
    }).mouseout(function(){
        var popid = $(this).attr("id").replace("cat-menu","");
	 popstatus[popid] = 0;
	 setTimeout( "removemenu()", 300 );
    });
 //---
    $(".online").click( function(){
	alert( "Функция в разработке!" );
    });
 //---
    $("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(event) {
		if (event.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() );	
	});

});


function removemenu( ) {
	$.each( popstatus, function(i,val) {
		if( !val ) $("#cat-menu" + i).css({ 'visibility' : 'hidden' });
	});
}

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[2]; // заменить если валюта другая по умолчанию - должна быть цена в рублях
	}
	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 = $('#sumtrue').val();
	var sum = parseFloat( sum );

	if( param == 0) {
		if( confirm( "Вы действительно хотите удалить позицию из корзины?" )) {
			$('#orderid' + id).css({'display':'none'});
			$('#sum').html( sumBetter( sum - count * price) );
			//alert( "Позиция удалена");
		} else {
			alert( "Удаление отменено" );
			return false;
		}
	} else {
		if( param == 2) {
			$('#sum').html( sumBetter( sum + count * price - parseFloat($('#sum' + id).html())));
			$('#sum' + id).html( (count * price).toFixed(2) );
		} else {
			alert( "В корзину добавлено " + count + " элементов");
		}
	}

	$.get("/project/phpfiles/_ajax.php", { id: id, action: 'order', param: param, count: count, price: price }, function(data) {
		//alert( "Позиция добавлена в корзину" );
	});
}


/**
*  COMMENTS
**/
	function addComment() {
		var pageid = $("#commid").val();
		var comment = $("#comment"+pageid).val();
		$.get("/project/phpfiles/_ajax.php", { action: 'comment', pageid: pageid, comment: comment }, function(data) {
			$("#comment-container").html(data);
			$("#comment"+pageid).val("");
		});
	}

	var isCtrl = false;
	$(document).keyup(function (e) {
		if(e.keyCode == 17) isCtrl=false;
	}).keydown(function (e) {
		if(e.keyCode == 17) isCtrl=true;
		if(e.keyCode == 13 && isCtrl == true) {
			addComment();
			return false;
		}
	});

/**
*  COMMENTS
**/

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, conf ) { // conf = true/false
	var xy = getScrollXY();
	var elem = $(window);

	if( !conf ) {
		var options = ['block', 'none', 550, 300 ]; // quest vis, conf vis, window width, window height
	} else {
		var options = ['none', 'block', 700, 500 ];
	}

	// show & hide form blocks: conf <-> quest

	$("#table-quest").css('display', options[0] );	
	$("#table-conf").css('display', options[1] );	
    	$("#form-header").html( name );
    	$("#tovarname").val( name );

	// animate window
	var xy = getScrollXY();	
	var newLeft = ( elem.width() - options[2] )/2;
    	var newTop =  ( elem.height() - options[3]  )/2 + xy[1] ;
    	$("#form-shadow").css( {'top': newTop,'left': newLeft, 'z-index': '99999', 'width': options[2], 'height': options[3] } );
    	$("#form-shadow").dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
    	$("#form-shadow").css({'visibility':'visible'});
}

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

/**
*  CONSULT
**/
function scanOpenSessions() {
	$.get("/project/phpfiles/_consult.php", { action: 'showactive', r: Math.random()}, function(data) {
		if( data && !opensess[1] ){	
			//if( confirm("Мы можем помочь Вам с выбором интересующего Вас продукта!\nРазрешите открыть сеанс связи с оператором?") ) {
				openConsult( 1, "" ); // cookie & ip
			//}
		}
	});
	scanopen = window.setTimeout( "scanOpenSessions()", 2000 );
}


var global = 0;
var opensess = [];
sess = new Array();
var clones = [];
var textarea = [];
var messages = [];
var shadow = [];
var dropshadow = [];
var operator = [];
var icall = [];
var heads = [];

function openConsult( id, page) {
	if( opensess[id] ) return;
	opensess[id] = 1;
	$clone = $("#form-container").clone().removeAttr("id");
	clones[id] = $clone;
	$clone.attr("id", "form-container" + id);
 	$("#consult-container").append($clone);
   	$clone.css({'position':'absolute','visibility':'visible','left' : (global*300 + 100) + "px",'top' : (global*30 + 30) + "px"});
	$clone.maxZIndex({ inc: 5 });
	dropshadow[id] = $clone.dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0, color: "black" });

	$.each( $(".form-header:noid:first"), function(i,val) {
		heads[id] = $(this);
		$(this).css({backgroundPosition: "50% 50%"});
	});

	$clone.draggable({ cursor: "move", handle: heads[id],
		start: function(event, ui) { dropshadow[id].remove(); },
		stop: function(event, ui) { dropshadow[id] = $(this).dropShadow({left: 10, top: 10, opacity: 0.3, blur: 0}); }
	});

	$clone.resizable({
		minHeight: 480,
		minWidth: 400,
   		start: function(event, ui) { dropshadow[id].remove(); },
		resize: function(event, ui) { 
			messages[id].css({ 'width' : '100%', 'height' : ($(this).height()-335)+'px'});
			textarea[id].css({ 'width' : '100%' });
		},
		stop: function(event, ui) { 
			dropshadow[id] = $(this).dropShadow({left: 10, top: 10, opacity: 0.3, blur: 0});
			messages[id].css({'width':'100%'});
			textarea[id].css({'width':'100%'});
		}
	});
	var isCtrl = false;
	$clone.keyup(function (e) {
		if(e.keyCode == 17) isCtrl=false;
	}).keydown(function (e) {
		if(e.keyCode == 17) isCtrl=true;
		if(e.keyCode == 13 && isCtrl == true) {
			var idc = $(this).attr("id").replace('form-container','');
			var txt = textarea[idc].val();
			textarea[idc].val("");
			$.get("/project/phpfiles/_consult.php", {message: txt}, function(data) {
				messages[idc].html(data);
			});
			return false;
		}
	});
	$.each( $(".btn-close:noid:first"), function(i,val) {
		$(this).attr("id", "close"+id);			
		$(this).click( function() {
			var idc = $(this).attr("id").replace('close','');
			clones[idc].remove();
			dropshadow[idc].remove();
			opensess[idc] = 0;
			// terminate call
			$.get("/project/phpfiles/_consult.php", { action: 'terminate', r: Math.random() });
		});
	});
	$.each( $(".ip:noid:first"), function(i,val) {
		$(this).attr("id", "ip"+id);
		$(this).html("<span>Сеанс связи</span>");
		document.getElementById("ip"+id).onselectstart = function() { return false; };
		$(this).unselectable = "on";
		$(this).css('-moz-user-select', 'none');   
		$(this).dblclick(function(e) { 
			var idc = $(this).attr("id").replace('ip','');
 			dropshadow[idc].remove();
			if( clones[idc].data('roll') == null ) {
				clones[idc].css({'overflow':'hidden', 'height':'470px'});
				clones[idc].stop().animate({'height' : '35px'},500, function() {
					dropshadow[idc] = clones[idc].dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
				});

				clones[idc].data('roll',1);
			} else {
				clones[idc].stop().animate({'height' : '470px'},500, function() {
					dropshadow[idc] = clones[idc].dropShadow({left: 10, top: 10, opacity: 0.2, blur: 0});
					messages[idc].css({ 'width' : '100%', 'height' : ($(this).height()-335)+'px'});
				});
				clones[idc].data('roll',null);
			}
		});
	});
	$.each( $(".symple:noid:first"), function(i,val) {
		$(this).attr("id", "textarea"+id);
		textarea[id] = $(this);
	});
	$.each( $(".input-call:noid:first"), function(i,val) {
		$(this).attr("id", "icall"+id);
		icall[id] = $(this);
	});
	$.each( $(".btn-call:noid:first"), function(i,val) {
		$(this).attr("id", "bcall"+id);
		$(this).click( function() {
			var idc = $(this).attr("id").replace('bcall','');
			var abonent = icall[idc].val();
			$(this).val("Соединяем...");
			$.get("/project/phpfiles/_consult.php", {abonent: abonent, action: 'call', page: page, r: Math.random()}, function(data) {
				var res = data.split("|");
				icall[idc].val(res[0]);
				if( res[1] == 1 ) {
					$(this).attr("disabled","disabled");
					$(this).val("Установлено соединение!");
				}
			});
		});
	});
	$.each( $(".messages:noid:first"), function(i,val) {
		messages[id] = $(this);
		refreshMess( id );
	});
	$.each( $(".btn-send:noid:first"), function(i,val) {
		$(this).attr("id", "send"+id);
		$(this).click( function() {
			var idc = $(this).attr("id").replace('send','');
			var txt = textarea[idc].val();
			textarea[idc].val("");
			$.get("/project/phpfiles/_consult.php", {message: txt}, function(data) {
				messages[idc].html(data);
			});
		});
	});

	// activate call
	$.get("/project/phpfiles/_consult.php", { action: 'activate', r: Math.random() }, function(data) {
		//
	});
}


function refreshMess( idc ) {
	//heads[idc].css({'background':'url(/project/img/c-header-animate.png)'});
	//heads[idc].animate({backgroundPosition:"(1000px 0)"}, {duration:1500});
	$.get("/project/phpfiles/_consult.php", { write: 1, message: textarea[idc].val(), r: Math.random() }, function(data) {
		messages[idc].html(data);
		messtimer = setTimeout( "refreshMess("+idc+")", 4000 );
		messages[idc].stop().scrollTo( { top: 7000, left: 0 } , 100 );
	});
}


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 ];
}