// ptsTour 12.10.10
// туры

function ptsTours(){
	
	var Config = {
		domain : "ptsagency.ru",
		//servpath : "http://ptsagency.ru/votes/pts_serv.php",
		servpath : "/votes/pts_serv.php",
		makepath : function(src){
			//var path = "http://www.gate.ptsgroup.ru/cgi-bin/Banners/banners.cgi?country_id=960&jsoncallback=?";
			//var path = "http://www.gate.ptsgroup.ru/cgi-bin/Banners/banners.cgi?country_id="+src+"&jsoncallback=?";
			return path;
		}
	}
	
	var ptsError = function(msg){
		alert(msg+"error");
	}
	
	//шаблонизатор
	var makeTemplate = function (str){
		var fn = new Function("obj",
			"var p=[],print=function(){p.push.apply(p,arguments);};" +
			// Introduce the data as local variables using with(){}
			"with(obj){p.push('" + document.getElementById(str).innerHTML
			  .replace(/[\r\t\n]/g, " ")
			  .split("<%").join("\t")
			  .replace(/((^|%>)[^\t]*)'/g, "$1\r")
			  .replace(/\t=(.*?)%>/g, "',$1,'")
			  .split("\t").join("');")
			  .split("%>").join("p.push('")
			  .split("\r").join("\\'") + "');} return p.join('');");
		return fn
	}
		
	this.loadData = function(cid, bnum){ // ид страны, ограничение по кол-ву банеров
		//var path = typeof src == "string"? src : Config.makepath(src);
		//var rnd = Math.floor(Math.random()*1000000)+1
		if(cid=="new"){
			var path = "http://www.gate.ptsgroup.ru/cgi-bin/Banners/banners.cgi?main_banners=1&jsoncallback=?";
			//var path = "http://www.gate.ptsgroup.ru/cgi-bin/Banners/banners.cgi?main_banners=1&jsoncallback=?"+rnd;
		} 
		else {
			var path = "http://www.gate.ptsgroup.ru/cgi-bin/Banners/banners.cgi?country_id="+cid+"&jsoncallback=?";
			//var path = "http://www.gate.ptsgroup.ru/cgi-bin/Banners/banners.cgi?country_id="+cid+"&jsoncallback=?"+rnd;
		}
		//var path = Config.makepath(cid);
		jQuery(".pts_loader").fadeIn(500);
		
		jQuery.getJSON(path, function(data){
			data? ptsBanner(data, bnum) : ptsError(path);
		});
	}
	
	
	// PTSmultivote v1.1
	this.ptsVote = function(){
		
		var vConfig = {
			pcont : jQuery("#site_poll_cont"),
			pid : jQuery("#site_poll_cont").attr("className"),
			pbody : ".poll_body",
			popts : jQuery(".poll_opt"),
			plabel : jQuery(".poll_lab"),
			pvote : jQuery("#poll_vote"),
			pact : "poll_act",
			ctime : 30,
			nocheck : false,
			presult : false,
			okmsg : "Спасибо за участие в опросе!",
			error : "Ошибка!"
		},
		pCheck = function(e){
			vConfig.pvote.fadeIn(1000);
			var parent = jQuery(this).closest(vConfig.pbody);
			parent.find("label").removeClass(vConfig.pact);
			e.target.name? jQuery(this).next().addClass(vConfig.pact) : jQuery(this).addClass(vConfig.pact).prev().attr("checked", true);			
		},
		pVote = function(){				
				var panswer = [];
				jQuery(vConfig.pbody).each(function(n,elem){					
					var ans = jQuery(this).find("label."+vConfig.pact);
					var answer = ans.length? ans.prev().attr("value") : 0;
					panswer.push(answer);
				});		
				pSend(panswer);			
		},
		pSend = function(vdata){
			//alert(vConfig.pid);
			jQuery.post(Config.servpath, {pid: vConfig.pid, poll:vdata, result:false},
					function(data){
						//alert(data);
						if(data && data==vConfig.pid){
							pComplite(vConfig.pid);
						} else {
							alert(vConfig.error);
							//return data;
						}	
					});
		},
		pComplite = function(pid){
			if(pid){
				var d = new Date();
				var t = d.getTime();
				jQuery.cookie(pid,t,{expires: vConfig.ctime, path: '/', domain: Config.domain});
			}		
			
				var v = vConfig.pvote.clone(true);
				vConfig.pvote.remove();
				var o = jQuery(vConfig.pbody).find("h4 ,form");
				var l = o.length-1;
				o.each(function(n,e){				
					var dir = e.name? '+=400' : '-=400';
					jQuery(e).animate({left:dir, "opacity": "toggle"},2000, function(){
						if(n==l){
							v.prependTo(vConfig.pcont);
							v.find("span").text(vConfig.okmsg);
							v.unbind();
							v.fadeIn(1000, function(){					
								jQuery(this).bind("click", function(){
									window.close();
								});
							});
							vConfig.presult? pResult() : false;
							
						}
					});
				});
		},
		pResult = function(){
			//var pdata
				if(!vConfig.presult){ //???
					vConfig.pvote.find("span").text(vConfig.okmsg);
					vConfig.pvote.fadeIn(1000);
					//alert("here");
					//vConfig.pvote.unbind("click");	
					return;
				}
				jQuery.post(Config.servpath, {pid: vConfig.pid, result : true},
						function(data){
							var js = eval("(" + data + ")");
							jQuery(".poll_stat_all").show();
							jQuery(".total").text(js[0]);
							jQuery(vConfig.pbody).each(function(n,e){
								var pos = n+1;													
								jQuery("<span/>",{html: '('+js[pos].total+')'}).appendTo(jQuery(this).find(".poll_topic"));							
								var ans = jQuery(this).find("div");							
								ans.each(function(num,e){
									var stat = js[pos][num];	
									var w = stat.perc? stat.perc+"%" : stat.perc;
									var answer = jQuery(this);									
									var atxt = answer.find("label").text();
									var aline = jQuery("<div/>",{html: atxt+'&nbsp;&nbsp;', className : 'poll_stat_a'});
									var a = jQuery("<span/>",{html: '('+stat.ans+')'});									
									answer.empty().addClass("poll_stat").before(aline.append(a));
									jQuery("<div/>",{html: w, width:w}).appendTo(answer);
								
								});
								
							});

							jQuery(vConfig.pbody).find("h4 ,form").animate({left:'0', "opacity": "toggle"},2000);
						});
					
					
		},
		pStart = function(){	
			vConfig.popts.attr("checked", false);
			vConfig.popts.bind("click", pCheck);
			vConfig.plabel.bind("click", pCheck);
			vConfig.pvote.bind("click", pVote);			
			jQuery(vConfig.pbody).find("h4 ,form").animate({left:'0', "opacity": "toggle"},2000);
		};
		
				
		if(!vConfig.pcont.length) return; //выходим
		
		var startwith = vConfig.nocheck? false : jQuery.cookie(vConfig.pid);
		startwith? pResult() : pStart();
		
		//vConfig.presult? pResult() : pStart() ;
			
	} //vote END mod:12.10.10
	
	
	var ptsBanner = function(data, bnum){
		
		if(bnum && bnum<data.length){ //ограничение и банеров больше
			var deln = data.length - bnum; //кол-во лишних	
			data = data.sort(function() {return 0.5 - Math.random()});					
		}
		
		
		//var js = jQuery("#pts_tour_holder");
		jQuery("#pts_loader").fadeIn(2000);
		//var temp = {};
		var banners = {};
		var bConfig = {
			tmplname : "pts_tmpl_readytour",
			imgpath : "/static/tours/images/",
			//imgn : Math.floor(Math.random()*3)+1, //случайная картинка
			place : jQuery("#pts_tour_holder")
		}
		
		var l = bnum? bnum : data.length;
		
		for(i = 0; i<l; i++){
			var id = data[i].BANNER_ID;
			
			//картинко
			
			//var imgrandom = Math.floor(Math.random()*3)+1;
			//alert(imgrandom);
			bConfig.imgn = Math.floor(Math.random()*3)+1;
			
			
			
			//bConfig.imgn = i+1;
			//data[i].QUIZ_ID = data[i].IS_QUIZ!=0? bConfig.quiz : "";
			data[i].QUIZ_ID = data[i].IS_QUIZ!=0? "<div class='pts_tour_hover' id='"+id+"'>ВИКТОРИНА</div>" : "";
			var priceObj = data[i].PRICES_LOOP[0];
			
			if(priceObj.DBL=="0"){
				continue;
			}
			delete data[i].PRICES_LOOP;
			var temp = jQuery.extend({},bConfig,data[i],priceObj);
			var b = {};
			for(var k in temp){
				b[k.toLowerCase()] = temp[k];
			}
			banners[id] = b;
			//в шаблон
			var tmpl = makeTemplate(bConfig.tmplname)(banners[id]);
			jQuery(tmpl).appendTo(bConfig.place);
			jQuery("#ready_tour_right").fadeIn(1000);
			jQuery(".pts_tour").fadeIn(1000).delay(1500);
			jQuery("#pts_loader").fadeOut(1500);
			jQuery(".pts_tour_hover").delay(2000).slideDown(1500);
			jQuery(".pts_tour_hover").click(function(e){
				e.stopImmediatePropagation();
				var r = "http://www.gate.ptsonline.ru/cgi-bin/Quiz/index.cgi?is_quiz=1&banner_id="+jQuery(this).attr("id");
				OpenMap(r,800,600,1);
			});
			
		}
		
		jQuery(".pts_loader").fadeOut(1000);
		
	} // ptsBanner
	

}
