// VARS
toogler = new Array();
toogler[1] = "closed";
toogler[2] = "closed";

// INIT
$(document).ready(function() {
	
	// Init Accordions
	if($("#accordion").length != 0){
		$("#accordion").tabs("#accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null,
			onBeforeClick:function(obj,index){
				this.getTabs().find("div").removeClass("opened");
				this.getTabs().find("div").addClass("closed");
				$("#accordion h2:eq("+index+") div").removeClass('closed');
				$("#accordion h2:eq("+index+") div").addClass('opened');
			},
			onClick:function(){}});
	}
	
	if($("#sidebar-accordion").length != 0){
		$("#sidebar-accordion").tabs("#sidebar-accordion div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null,
			onBeforeClick:function(obj,index){
				
				this.getTabs().find("div").removeClass("opened");
				this.getTabs().find("div").addClass("closed");
				$("#sidebar-accordion h2:eq("+index+") div").removeClass('closed');
				$("#sidebar-accordion h2:eq("+index+") div").addClass('opened');
				
			},
			onClick:function(){}});
	}
	
	// Correct Sidebar Bottom Line
	sidebarCorrection();
	
	// Init Widget on Widget Page
	if($('#widget-detailwrap').length != 0){
		$("#widget-detailwrap").scrollable({circular:true,speed:600,easing:"easeOutCubic",onSeek:function(){
			showHeadline(this.getIndex());																								  
		}}).navigator(".navi");
		
		api = $("#widget-detailwrap").data("scrollable");
		
		if(widgetSeeker!=1){
			api.seekTo(widgetSeeker-1,0);
		}
		api.focus();
		
		$('.cloned [name|="form-fragen"]').attr("name","form-fragen-cloned");
		$('.cloned [id|="frmFragen"]').attr("id","frmFragen-cloned");

		widgets_initGoogleMap(); 
	}
	
	// Init Tankstellen Widget on Real Widget
	if($('body.widget-frame').length != 0){
		widgets_initGoogleMap(); 	
	}
	
	// Init Tell a Friend Trigger
	if(segment1 != "embed"){
		var trigger = $(".tellafriendtrigger").overlay({
			mask: {
				color: '#efedee',
				loadSpeed: 200,
				opacity: 0.9
			},
			closeOnClick: true
		});	
	}
	
	// Init Contact Form
	if($('#contact_form').length != 0){
		$("#contact_form").bind("submit", function(event) {
			event.preventDefault();
			
			$("body").scrollTo('body', 400, {offset:-100} );
			
			$.ajax({
				type: "POST",
				url: 'http://avia.ch/'+ lang +'/main/success',
				data: $('#contact_form').serialize(),
				success: function(response){
					
					if(response=="success"){
						$("#error").hide();
						$("#success").show();
						$("#contact_form").resetForm();
					}else{
						$("#success").hide();
						$("#error #ul-cont").empty();
						
						var html = "<ul>";
						var content = $(response).find('div.article ul').text();
						
						if(content.indexOf("Nachname")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Nachname']+" </li>";
						}
						if(content.indexOf("Vorname")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Vorname']+" </li>";
						}
						if(content.indexOf("Ort")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Ort']+" </li>";
						}
						if(content.indexOf("Telefon")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Telefon']+" </li>";
						}
						if(content.indexOf("E-Mail")!=-1){
							html = html + "<li> "+frmKontaktError[0]['E-Mail']+" </li>";
						}
						if(content.indexOf("Nachricht")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Nachricht']+" </li>";
						}
						
						html = html + "</ul>";
						
						$("#error #ul-cont").html(html);
						$("#error").show();
						//$("body").scrollTo('#error', 400, {offset:-100} );
					} 
				}
			});
			
		});
	}
	
	// INIT BESTELLFORMULAR
	if($('#shop_form').length != 0){
		$("#shop_form").bind("submit", function(event) {
			event.preventDefault();
			
			$("body").scrollTo('body', 400, {offset:-100} );
			
			$.ajax({
				type: "POST",
				url: 'http://avia.ch/'+ lang +'/main/success',
				data: $('#shop_form').serialize(),
				success: function(response){
					
					if(response=="success"){
						$("#error").hide();
						$("#success").show();
						$("#shop_form").resetForm();
					}else{
						$("#success").hide();
						$("#error #ul-cont").empty();
						
						var html = "<ul>";
						var content = $(response).find('div.article ul').text();
						
						if(content.indexOf("Anrede")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Anrede']+" </li>";
						}
						if(content.indexOf("Nachname")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Nachname']+" </li>";
						}
						if(content.indexOf("Vorname")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Vorname']+" </li>";
						}
						if(content.indexOf("Strasse")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Strasse']+" </li>";
						}
						if(content.indexOf("PLZ")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Plz']+" </li>";
						}
						if(content.indexOf("Ort")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Ort']+" </li>";
						}
						if(content.indexOf("Land")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Land']+" </li>";
						}
						if(content.indexOf("Telefon")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Telefon']+" </li>";
						}
						if(content.indexOf("E-Mail")!=-1){
							html = html + "<li> "+frmKontaktError[0]['E-Mail']+" </li>";
						}
						if(content.indexOf("Anzahl")!=-1){
							html = html + "<li> "+frmKontaktError[0]['Anzahl']+" </li>";
						}
						
						html = html + "</ul>";
						
						$("#error #ul-cont").html(html);
						$("#error").show();
						//$("body").scrollTo('#error', 400, {offset:-100} );
					} 
				}
			});
			
		});
	}
	
});

function sidebarCorrection(){
	if($("#sidebar").height() > $("#article-main").height() ){
		$(".sidebar-teaser .teaser-handle .teaser:last").css("border-bottom","none");
	}
}

function prevWidget(){
	api.prev();
}

function nextWidget(){
	api.next();	
}

function showHeadline(id){
	if(id == -1){return;}
	var headlines = $("[id*=headline]");
	id++;
	if(id > headlines.size()) id = 1;

	$("[id*=headline]");
	$('#headline-'+id)
        $("[id*=headline]:not(#headline-"+id+")").fadeOut(300, function() {
	$('#headline-'+id).fadeIn(300, function() {
		// Animation complete
	});
    });
}


function toogleComments(){
	if($("#social .btn a").hasClass('opened')){
		$("#social .btn a").removeClass("act");
		$("#social .btn a").removeClass("opened");
		$("#social .btn a").addClass("closed");
	}else{
		$("#social .btn a").removeClass("closed");
		$("#social .btn a").addClass("opened");
		$("#social .btn a").addClass("act");	
	}
	$("#comments").slideToggle('slow', function() {
    	// Animation complete.
  	});
}

function sendTellAFriend(){
	$.ajax({
		type: "POST",
		url: 'http://avia.ch/'+ lang +'/php/tellafriend',
		data: $('#frmTellAFriend').serialize(),
		success: function(data){
			if(data!="success"){
				$("p#message").html(tellafriend_error).css("color","#F00").show();
				data = $.parseJSON(data);
				$.each(data, function(index, value) {
					$("#"+index).css({"border":"1px solid #F00","color":"#F00"});
				});
			}else{
				document.forms['frmTellAFriend'].reset();
				$("p#message").html(tellafriend_success).removeAttr("style").show();
				$('input[type=text]').removeAttr("style");
			}
		}
	});
}

function gqc(searchvalue){
	searchvalue = searchvalue.innerHTML;
	$.ajax({
		type: "POST",
		url: 'http://avia.ch/'+ lang +'/main/fragen-kategorien',
		data: {
			searchvalue:searchvalue
		},
		success: function(data){
			data = trim(data);
			if(data==""){
				html = "<p class='newscaterror'>"+ newscaterror+" "+searchvalue+"</p>";
			}else{
				html = "<ul>"+data+"</ul>";	
			}
			$("#question-wrap").html(html);
		}
	});
}

function rollOverSmpl(obj){
	if(typeof(obj)!="object"){
	obj = $(obj);
	}
	var img = obj.firstChild;
	var oldsrc = img.src;
	OldSrc = oldsrc;
	var endung = oldsrc.slice(-4);
	var start = oldsrc.substr(0,(oldsrc.length-4));
	var newsrc = start+"-over"+endung;
	img.src = newsrc;
}
function rollOutSmpl(obj){
	if(typeof(obj)!="object"){
	obj = $(obj);
	}
	var img = obj.firstChild;
	img.src = OldSrc;
	OldSrc = "";
} 

$.tools.tabs.addEffect("slide", function(i, done) {
										 
	this.getPanes().slideUp(500,'easeOutCubic',function(){
		
	});
	
	this.getPanes().eq(i).slideDown(500,'easeOutCubic',function()  {
		done.call();
	});
	
});

function share(text,url,plattform){	
	var windowurl;
	if(plattform=="facebook"){
		if(lang=="de"){
			locale = "de_DE";	
		}
		if(lang=="fr"){
			locale = "fr_FR";	
		}
		if(lang=="it"){
			locale = "it_IT";	
		}
		windowurl = "http://www.facebook.com/sharer.php?locale="+locale+"&u="+url+"&t="+text+"";		
	}else{
		windowurl = "http://twitter.com/share?_=1299669220921&count=horizontal&text="+text+"&url="+url+"&via=twitter";	
	}
	
	fenster = window.open(windowurl, "", "width=505,height=346,status=yes,scrollbars=no,resizable=no");
	fenster.focus();
}

function toogleWidgetEmbedCode(id){	
	if(id == 1){
		if(toogler[id] == "closed"){
			toogler[id] = "opened";
			$(':not(.cloned) #map-canvas').animate({
				height: '182px'
				}, 300, function() {
					// Animation complete.
				}
			);		
		}else{
			toogler[id] = "closed";
			$(':not(.cloned) #map-canvas').animate({
				height: '239px'
				}, 300, function() {
					// Animation complete.
				}
			);	
		}
	}
	if(id == 2){
		if(toogler[id] == "closed"){
			toogler[id] = "opened";
			//$('#test').css("height","86px");
			$(':not(.cloned) #frage').animate({
				height: '130px'
				}, 300, function() {
					// Animation complete.
				}
			);
			$(':not(.cloned) .widget-frage-success').animate({
				height: '199px'
				}, 300, function() {
					// Animation complete.
				}
			);
		}else{
			toogler[id] = "closed";
			//$('#test').css("height","186px");
			$(':not(.cloned) #frage, :not(.cloned) .widget-frage-success').animate({
				height: '186px'
				}, 300, function() {
					// Animation complete.
				}
			);
			$(':not(.cloned) .widget-frage-success').animate({
				height: '255px'
				}, 300, function() {
					// Animation complete.
				}
			);
		}
	}
}

function createNewQuestion(){
	$(":not(.cloned) #frage,:not(.cloned) #email").css("border","1px solid #A09691");
	$.ajax({
		type: "POST",
		url: 'http://avia.ch/'+ lang +'/php/createNewQuestion',
		data: $('#frmFragen').serialize(),
		success: function(data){
			if(data!="success"){
				data = $.parseJSON(data);
				$.each(data, function(index, value) {
					$(":not(.cloned) #"+index).css({"border":"1px solid #F00","color":"#F00"});
				});
			}else{
				$(':not(.cloned) #frmFragen').before('<p class="widget-frage-success">Besten Dank, wir haben Ihre Frage erhalten und werden uns umgehen melden.</p>');
				$(':not(.cloned) #frmFragen, .btn').remove();
			}
		}
	});
}

function searchStations(){
	searchvalue = $("#frmStations").val();
	if(searchvalue==""){return;}
	$.ajax({
		type: "POST",
		url: 'http://avia.ch/'+ lang +'/php/search-station',
		data: {
			searchvalue:searchvalue
		},
		success: function(data){
			$("#searchmessage").html("");
			data = $.parseJSON(data);
			if(data==""){$("#searchmessage").html(tankstellen_suche);return;}
			var searchPosition = new google.maps.LatLng(data[0]["geo_y"],data[0]["geo_x"]);
			map.setCenter(searchPosition);
			map.setZoom(14);
		}
	});
}

function widgets_initGoogleMap(){
	var myOptions = {
		zoom: 11,
		mapTypeControl:false,
		navigationControl:true,
		scaleControl:false,
		center: new google.maps.LatLng(47.302548525618576,8.590997457504272),
		//mapTypeId: google.maps.MapTypeId.SATELLITE
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
	infowindow = new google.maps.InfoWindow({
		content: "",
		zIndex:5000
	});
	widgets_fillMapWithStations();
}


function AO(lat, lng, id, html, autobahn, shop, bedient, autovertretung, reka, diesel, erdgas, wash, sb_box){
	widgets_createMarker(lat, lng, id, html, autobahn, shop, bedient, autovertretung, reka, diesel, erdgas, wash, sb_box);
}
	
function widgets_createMarker(lat, lng, id, html, autobahn, shop, bedient, autovertretung, reka, diesel, erdgas, wash, sb_box){       		
	var myLatlng = new google.maps.LatLng(lat, lng);
	var image;
	if (autobahn){
		image = "station_green";
	}
	else{
		if(shop){
			image = "station_blue";
		}else{
			image = "station_red";
		}
	}
	image = "http://avia.ch//default_site/images/" + image + ".png";
	var marker = new google.maps.Marker({
		position: myLatlng,
		map: map,
		title:"Hello World!",
		icon:image,
		zIndex:4000
	}); 
	var t = "<span class=normaltext>" + html;
		
		if (shop || bedient || autovertretung || reka || diesel || erdgas || wash || sb_box)
		t += "<br/>";
		
		if (shop)
		t += html_image('shop');
		
		if (bedient)
		t += html_image('bedient');
		
		if (autovertretung)
		t += html_image('autovertretung');
		
		if (reka)
		t += html_image('reka');
		
		if (diesel)
		t += html_image('diesel');
		
		if (erdgas)
		t += html_image('erdgas');
		
		if (wash)
		t += html_image('waschanlage');
		
		if (sb_box)
		t += html_image('sbbox');
		
		if(isEmbed){
			t += "<br /><a href='http://avia.ch/"+lang+"/"+tankstellen_page_url+"/"+id+"' target='_blank'>"+tankstellen_detail+"</a></span>";
		}else{
			t += "<br /><a href='http://avia.ch/"+lang+"/"+tankstellen_page_url+"/"+id+"'>"+tankstellen_detail+"</a></span>";	
		}
	
	google.maps.event.addListener(marker, 'mouseover', function() {
		infowindow.setContent(t);
		infowindow.open(map,marker);
	});
}

function html_image(src){
	return "<img src='http://avia.ch//default_site/images/icon_" + src + ".png' border='0' alt='' /> ";
}

//Javascript trim, ltrim, rtrim http://www.webtoolkit.info/
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
