function ProductButton(id,title,productDescriptions) {
	this.id = id;
	this.title = title;
	this.productDescriptions= productDescriptions;	
}
function ProductDescription (id,title,subtitle,image,offers,productMenuItems) {
	this.id=id;
	this.title=title;
	this.subtitle=subtitle;
	this.image=image;
	this.offers=offers;
	this.productMenuItems=productMenuItems;
}
function ProductMenuItem (id,title,subtitle) {
	this.id=id;
	this.title=title;	
	this.subtitle=subtitle;	
}

pn_selected = 0;
pn_animation = false;

$(document).ready(function(){
	var buttonsContainer = $("#pn_buttons");
	var descriptionsContainer = $("#teasers");
	descriptionsContainerHtml = "";
	buttonsContainerHtml = '<div style="width:370px;"><div style="width:370px;height:0;overflow-y:hidden"></div>';
	var ie6=$.browser.msie&&($.browser.version == "6.0")&&!window.XMLHttpRequest;
	for (btnId in products) {
		var productButton = products[btnId];		
		var pnId = "pb_"+btnId;
			
			
		if (btnId>0) {
			buttonsContainerHtml += '<div class="pn_button" rel="'+productButton.id+'" id="' + pnId + '"><div class="bottom">'+ productButton.title +'</div><div class="top"></div><div class="mask_l"></div><div class="mask_r"></div></div>';
		}

		for (descId in productButton.productDescriptions) {
			var productDescription = productButton.productDescriptions[descId];
			//alert(productDescription.offers);
			var pdId = "pd_"+productDescription.id;
			
			var siblingDescLinks = "";
			for (var sId in productButton.productDescriptions) {
				if (sId != descId) {
					siblingDescLinks += '<div class="siblingDescLink" rel="' + productButton.productDescriptions[sId].id + '">'+ ((productButton.productDescriptions[sId].subtitle)?productButton.productDescriptions[sId].subtitle:productButton.productDescriptions[sId].title) +'</div>';
				}
			}
		


			var menuItemsLinks = "";
			for (var mId in productDescription.productMenuItems) {
				if (productDescription.productMenuItems.length / 2 == Math.floor(productDescription.productMenuItems.length / 2))
					leftMargin = 60-productDescription.productMenuItems.length*7+7*Math.floor(( productDescription.productMenuItems.length/2 - Math.abs(mId - productDescription.productMenuItems.length/2  + 0.5)));
				else
					leftMargin = 60-productDescription.productMenuItems.length*7+7*(Math.floor(productDescription.productMenuItems.length/2)- Math.abs(mId - Math.floor(productDescription.productMenuItems.length/2)));

				menuItemsLinks += '<a rel="pi_' + productDescription.productMenuItems[mId].id + '" style="margin-left:'+leftMargin+'px" href="/index.php?id='+  productDescription.productMenuItems[mId].id  +'">'+ ((productDescription.productMenuItems[mId].subtitle)?productDescription.productMenuItems[mId].subtitle:productDescription.productMenuItems[mId].title) +'</a>';
			}
			
			
			descriptionsContainerHtml +='<div id="'+pdId+'" class="productDescription">';
			if (ie6) {
				descriptionsContainerHtml += '<div class="image" style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=/uploads/tx_templavoila/'+ productDescription.image +', sizingsMethod=image)"></div>';				
			} else {
				descriptionsContainerHtml += '<div class="image" style="background-image:url(/uploads/tx_templavoila/'+ productDescription.image +')"></div>';
			}
			
/*			descriptionsContainerHtml += '\
        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="content"><tr>\
        <td colspan="3" class="header">\
                  <h1>'+productDescription.title+'</h1>'+ siblingDescLinks +'\
        </td></tr>\
        <tr>\
        	<td class="menu">'+ menuItemsLinks +'</td>\
        	<td class="descr">' + utf8_decode(unescape(productDescription.offers)) + '\
			</td><td>&nbsp;</td></tr>\
            <tr> <td colspan="3" class="footer"><table width="100%" border="0" cellspacing="0" cellpadding="0">\
              <tr>\
                <td width="10%" valign="top">Получить&nbsp;полис:&nbsp;&nbsp;&nbsp;</td>\
                <td valign="top"><a href="#">в офисе</a>&nbsp; &nbsp; &nbsp; <a href="#">у&nbsp;выездного&nbsp;менеджера</a></td>\
              </tr>\
            </table></td></tr></table>\
            </div>\
						     ';
*/




			descriptionsContainerHtml += '\
	<div class="header"><h1>'+productDescription.title+'</h1>'+ siblingDescLinks +'\</div>\
        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="content"><tr>\
        	<td class="menu">'+ menuItemsLinks +'</td>\
        	<td class="descr">' + utf8_decode(unescape(productDescription.offers)) + '\
			</td></tr>\
            </table>\
	    <div class="footer">Получить&nbsp;полис:&nbsp;&nbsp;&nbsp;<a href="/branches/">в офисе</a>&nbsp; &nbsp; &nbsp; <a href="#" class="preorderLink">у&nbsp;выездного&nbsp;агента</a></div>\
            </div>\
						     ';







			
		}
		

	}
	buttonsContainerHtml +="</div>"
	descriptionsContainer.html(descriptionsContainerHtml);
	buttonsContainer.html(buttonsContainerHtml);


	$(".siblingDescLink").click(function() {
		var newPdId = $(this).attr('rel');
		for (var i in products)
			if (products[i].id == pn_selected) {
				for (var j in products[i].productDescriptions) 
					if (products[i].productDescriptions[j].id == newPdId) {
						pdSelect(products[i].productDescriptions[j]);
						break;
					}
				break;
			}		
	});

	$(".pn_button").click(function() {
		pnSelect(this);
	});
	
	$(".productDescription").each(function(){
		var offers = $(this).find(".descr DIV.csc-default")		
		offers.hide();
		if (offers.length)
			offers.eq(Math.floor(Math.random()*offers.length)).show();
	});

	pnSelect();
	

	
	
			
	consultantsTxt = '*';
	setConsultantsIntervalTimeout = 0;
// 	Включить обратно после отладки!	

	$(window).resize(function(){
							  
    			$("#consultants").hide();

			  consultantsTxt = '*'; 
			  clearInterval(refreshConsultantsInterval);
			  if (setConsultantsIntervalTimeout) 	window.clearTimeout(setConsultantsIntervalTimeout);
			  setConsultantsIntervalTimeout = window.setTimeout(setConsultantsInterval,300);
	} );

	setConsultantsInterval()

	
	
})

function pnSelect(buttonObj) {
	if (pn_animation) return;

	if (pn_selected) {
		pn_animation = true;
		buttonObj = $(buttonObj);
		var pnId = buttonObj.attr('rel');

		var newProduct, oldProduct;
		
		for (var i in products) {
			if (products[i].id == pnId) newProduct = products[i];
			if (products[i].id == pn_selected) oldProduct = products[i]; 
		}

		pdSelect(newProduct.productDescriptions[0]);

		
		buttonObj.find(".top").html(oldProduct.title).animate({marginLeft:0},{
			duration:400,
			complete:function() {
				$(this).siblings(".bottom").html($(this).html())
				$(this).css({marginLeft:-166});
				var old_pn_selected = pn_selected ;
				//pn_selected = $(this).parent().data("pnId");
				//$(this).parent().data("pnId", old_pn_selected) ;
				pn_selected = $(this).parent().attr("rel");
				$(this).parent().attr("rel", old_pn_selected) ;
			}
		});
		
//		$("#pd_" +pn_selected).show();
//		$("#pd_" +pnId).hide();
	} else {
		productDescription = products[0].productDescriptions[0];
		$("#pd_" + productDescription.id).show();
		
		pn_selected = products[0].id;
		pd_selected = productDescription.id;
		
	}
	$(".preorderLink").tooltip({
		position: "bottom center",
		effect: "slide", 
		opacity: 0.9,
		tip:'#preorderformtooltip',
		delay:300
	});
	
}

function pdSelect(productDescription) {
	pn_animation = true;
	$("#pn_description .arrow").html(productDescription.title)
		.css({'left':-$("#pn_description").width()+"px",'background-position':"100% 0",'display':'none'})
		.show()
		.animate({left:0},{
			duration:400,
			complete:function() {
				$("#pd_" + pd_selected).hide();
				pd_selected = productDescription.id;
				//$(this).css({backgroundPosition:"0 0"})			
				$("#pd_"  + pd_selected).show();
				
				}
			})
		.animate({top:0},{duration:800})
		.animate({left:$("#pn_description").width()},{
			duration:400,
			complete:function() {
				$(this).hide();
				pn_animation = false;

				
				}
			})
}

 function utf8_decode (utftext) {
	var string = "";
	var i = 0;
	var c = c1 = c2 = 0;

	while ( i < utftext.length ) {

		c = utftext.charCodeAt(i);

		if (c < 128) {
			string += String.fromCharCode(c);
			i++;
		}
		else if((c > 191) && (c < 224)) {
			c2 = utftext.charCodeAt(i+1);
			string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
			i += 2;
		}
		else {
			c2 = utftext.charCodeAt(i+1);
			c3 = utftext.charCodeAt(i+2);
			string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
			i += 3;
		}

	}

	return string;
}
 
 
 

function setConsultantsInterval() {
	refreshConsultantsInterval = setInterval(refreshConsultants,3000);
//	refreshConsultants();	
}
function refreshConsultants() {
	$.getJSON("/livehelp/operators.php?lang=ru&jsoncallback=?",
        function(data){
			var newconsultants="";
			for (consultant in data) {
				newconsultants += data[consultant].operatorid +",";
			}
			if  (consultantsTxt != newconsultants) {
				consultantsTxt = newconsultants;
				refreshConsultantsList(data);
			}
        });
}

function refreshConsultantsList(consultants) {

	$("#consultants").html("");
	var online = 0;
	for (i in consultants) if (consultants[i].status==1) online++;
	if (consultants.length) {
		if (online==0) {
			$("#consultants_count").html("К сожалению, сейчас все консультанты заняты. Пожалуйста, подождите несколько минут.<br><br>");
			$("#consultationInput INPUT").attr({disabled:true});
			$("#consultationInput").fadeTo("slow",0.3);
			$("#consultation").css("background-position", "100% -225px");
		}
		else {
			if (online ==1 )
				$("#consultants_count").html("Один из наших консультантов находится online, вы можете обратиться за консультацией к нему:");
			else
				
				$("#consultants_count").html("Сейчас "+ online + num(online," наш консультант находится"," наших консультанта находятся"," наших консультантов находятся") +" online, вы можете выбрать, чья консультация вам необходима:");

			$("#consultationInput INPUT").attr({disabled:false});
			$("#consultationInput").fadeTo("slow",1);
			$("#consultation").css("background-position", "100% 0")

		}
		var ul = '<ul class="list">'
		for  (consultant in consultants) {
			isoffline = (consultants[consultant].status==0)?"<div class=offline>Консультант занят</div>":"<div class=online>Консультант свободен</div>";
			ul += '<li><div class="handle"><div class="face" style="background-image:url(/livehelp/images/avatar/th_'+ consultants[consultant].operatorid +'.jpg)"></div></div><div class="name">' +  consultants[consultant].vclocalename + '</div><div class="office"><!--a href="'+consultants[consultant].vclocaldescription+'"-->' + consultants[consultant].vclocalname + '<!--/a--></div>'+isoffline+'</li>';
		}
		ul += "</ul>";
		$("#consultants").html(ul);
		$("#consultants").show();
		
		$("#consultants .list").hrzAccordion({eventTrigger:"mouseover",openOnLoad:"1", handlePosition:"left", closeOpenAnimation: 1});
		


	}
	
	else {
		$("#consultants").html('<br><br>');
		$("#consultants_count").html("К сожалению, в настоящий момент нет свободных консультантов.<br><br>");
	}

}

function webimOpen() {
	if (navigator.userAgent.toLowerCase().indexOf('opera') != -1 && window.event.preventDefault)
		window.event.preventDefault();
	
//	this.newWindow = window.open('/livehelp/client.php?locale=ru&url='+escape(document.location.href)+'&referrer='+escape(document.referrer)+'&hello='+escape($("#hello").val()),
//				     'webim', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');
	this.newWindow = window.open('/livehelp/client.php?locale=ru&referrer='+escape(document.referrer)+'&style=default&survey=on&info=&email=&message='+encodeURIComponent($("#hello").val()),
				     'webim', 'toolbar=0,scrollbars=0,location=0,status=1,menubar=0,width=640,height=480,resizable=1');
	this.newWindow.focus();
	this.newWindow.opener=window;
	return false;
}

function num(number,c1,c2,c5){
	number=number.toString();
	if ((number.substr(-1)=="1") && (number.substr(-2)!="11")) return c1;
	if ((number.substr(-2,1) != "1") && ("234".indexOf(number.substr(-1))>=0)) return c2;
	return c5;
}


 
