/* Global variables */
var body; // the body
var diven; // big black
var div_i; // info in the big black
var divaa; // terms & conditions div
var img_close; // close button
var steg1; // step 1 div
var steg2; // step 2 div
var div_clear; // clear div
var div_2; // accept div
var leftContent; // content div
var tooltip; // content div
var a1;
var	h1;
var	h2;
var txt1;
var locked = false; // if other window is up this should be true in order to prevent from submit form again
var q1; // Div for questionIMG 1
var q2; // Div for questionIMG 2
var q1IMG; // questionIMG 1
var q2IMG; // questionIMG 2
var input1focused = false;
var input2focused = false;
var input3focused = false;
var free_height;
var five_height;
	
/* Initialize */
$(document).ready(function(){
	free_height = $("#leftContent").height();
	five_height = $("#mainRight").height();

	body = document.getElementById('bodie');
	steg1 = document.getElementById('s1');
	steg2 = document.getElementById('s2');
	q1 = document.getElementById('q1');
	q2 = document.getElementById('q2');
	q1IMG = document.getElementById('q1IMG');
	q2IMG = document.getElementById('q2IMG');
	leftContent = document.getElementById('leftContent');
	tooltip = document.getElementById('tooltip');
	
	// BIG BLACK
	diven = document.createElement("DIV");
	$(diven).addClass("big_black");
	$(diven).css('opacity',0);
	$(diven).css('height',$(document).height());
	$(diven).hide();
	$(body).append(diven);
	
	// IN THE BIG BLACK
	div_i = document.createElement("DIV");
	$(div_i).addClass("in_black");
	$(div_i).css('opacity',0);
	$(div_i).hide();
	$(body).append(div_i);

	// CLOSE BUTTON
	img_close = document.createElement("IMG");
	$(img_close).addClass("closebut");
	$(img_close).attr("src","img/close.gif");
	$(img_close).click(function() {removeDivs();});
	
	// LODING PIC
	imga = document.createElement("IMG");
	$(imga).attr("src","img/loading.gif");
	$(imga).addClass("picPadding20Top");
	
	// CLEAR DIV
	div_clear = document.createElement("DIV");
	$(div_clear).addClass("div_clear");

	
	// DIV 2
	div_2 = document.createElement("DIV");
	$(div_2).addClass("accept");
	
	// A LINK
	a1 = document.createElement("A");
	
	// H1
	h1 = document.createElement("H1");
	
	// H2
	h2 = document.createElement("H2");
	
	// H3
	h3 = document.createElement("H3");
	
	// TEXTAREA
	txt1 = document.createElement("TEXTAREA");
	
	// TERMS & CONDITIONS DIV 
	divaa = document.createElement("DIV");
	
	// SELECT INPUT NR
	$(document.getElementById('nr')).select();
	
	// EMAILINPUT
	$('#input3').elastic();
	
	// FUNCTIONS
	$(document.getElementById('input1')).focus(function() {  
		$("#coverContent").show();
	});  
	$(document.getElementById('input1')).blur(function() {  
		$("#coverContent").hide();
	});
	$(document.getElementById('input2')).focus(function() {  
		$(q1IMG).css("visibility","hidden");
		input2focused = true;
		var pos = $(this).offset();  
		$(tooltip).css( { "left": (pos.left-275) + "px", "top":(pos.top-28)+ "px" } );
		$(tooltip).show();
		$("#coverContent").show();
		$("#TTtext").html("<h2>Ditt referensnummer</h2><p><em>- obligatoriskt för gratis uppdatering</em><br />Detta nummer anger du för att vi skall veta att det är till just dig vi ger gratis uppdateringar. Ditt referensnummer hittar du under \"Få gratis uppdateringar\" i Call40 programvaran på din telefon.</p><p>Lämna tomt om du inte har programvaran och bara vill tipsa vänner utan att få gratis uppdateringar.</p>");
	});  
	$(document.getElementById('input2')).blur(function() {  
		$(q1IMG).css("visibility","visible");
		input2focused = false;
		$(tooltip).hide();
		$("#coverContent").hide();
	});
	$(document.getElementById('input3')).focus(function() {  
		$(q2IMG).css("visibility","hidden");
		input3focused = true;
		var pos = $(this).offset();  
		$(tooltip).css( { "left": (pos.left-275) + "px", "top":(pos.top-36)+ "px" } );
		$(tooltip).show();
		$("#coverContent").show();
		$("#TTtext").html("<h2>Epostadresser till de som tipsas</h2><p><em>- obligatoriskt</em><br />Här anger du epostadresser till de som skall tipsas. Separera varje epostadress med ny rad.</p>");
	});  
	$(document.getElementById('input3')).blur(function() {  
		$(q2IMG).css("visibility","visible");
		input3focused = false;
		$(tooltip).hide();
		$("#coverContent").hide();
	});

	$(document.getElementById('q1_1')).mouseover(function(){
		if (!input2focused && !input3focused){
			$(q1IMG).css("visibility","hidden");
			var pos = $(this).offset();  
			$(tooltip).css( { "left": (pos.left-275) + "px", "top":(pos.top-28)+ "px" } );
			$(tooltip).show();
			//$("#coverContent").show();
			$("#TTtext").html("<h2>Ditt referensnummer</h2><p><em>- obligatoriskt för gratis uppdatering</em><br />Detta nummer anger du för att vi skall veta att det är till just dig vi ger gratis uppdateringar. Ditt referensnummer hittar du under \"Få gratis uppdateringar\" i Call40 programvaran på din telefon.</p><p>Lämna tomt om du inte har programvaran och bara vill tipsa vänner utan att få gratis uppdateringar.</p>");
		}
    });
	$(document.getElementById('q1_1')).mouseout(function(){
		if (!input2focused && !input3focused){
			$(q1IMG).css("visibility","visible");
			$(tooltip).hide();
			//$("#coverContent").hide();	
		}
    });
	$(document.getElementById('emails')).mouseover(function(){
		if (!input2focused && !input3focused){
			$(q2IMG).css("visibility","hidden");
			var pos = $(this).offset();  
			$(tooltip).css( { "left": (pos.left-275) + "px", "top":(pos.top-21)+ "px" } );
			$(tooltip).show();
			//$("#coverContent").show();
			$("#TTtext").html("<h2>Epostadresser till de som tipsas</h2><p><em>- obligatoriskt</em><br />Här anger du epostadresser till de som skall tipsas. Separera varje epostadress med ny rad.</p>");
		}
    });
	$(document.getElementById('emails')).mouseout(function(){
		if (!input2focused && !input3focused){
			$(q2IMG).css("visibility","visible");
			$(tooltip).hide();
			//$("#coverContent").hide();	
		}
    });


	$(".send").click(function() {
		$("#formCheck1").css('visibility','visible');
		if (!validateName(document.getElementById('input1').value)){
			$("#input1").focus();
			$("#formCheck1").attr("src", "img/error.gif");
			return false;
		} else
			$("#formCheck1").attr("src", "img/checked.gif");
			
		validateRef(document.getElementById('input2').value);
		return false;	
	});
	
	$("#first1000").click(function() {
		var info = "Som en kampanj under lanseringen av vår betaversion ger vi de 1000 första kunderna den första uppdateringen gratis. Värde 20 kr. Antal kunder just nu: ";
		error("1000 första gratis!",info + "laddar...");
		$.ajax({
			type: "GET",
			url: "php/nr_customers/",
			success: function(msg){
				if (msg != false){
					error("1000 första gratis!",info + msg);
				} else {
					error("1000 första gratis!",info + "kunde inte laddas.");
				}
			}
		});
		return false;
	});
	$("#head_free").mouseover(function (){
		$("#gratis_upp").addClass("h2_right_div_over");
	});
	$("#head_free").mouseout(function (){
		$("#gratis_upp").removeClass("h2_right_div_over");
	});
	$("#head_free").click(function (){
		if ($("#mainRight").height() == 60)
			$("#mainRight").animate({ height: free_height+"px" }, 700);
		else
			$("#mainRight").animate({ height: "60px" }, 700);
	});
	
	$("#head_five").mouseover(function (){
		$("#fem_steg").addClass("h2_right_div_over");
	});
	$("#head_five").mouseout(function (){
		$("#fem_steg").removeClass("h2_right_div_over");
	});
	$("#head_five").click(function (){
		if ($("#leftContent").height() == 60)
			$("#leftContent").animate({ height: free_height+"px" }, 700);
		else
			$("#leftContent").animate({ height: "60px" }, 700);
	});
	
	var cache = [];
	var cacheImage = document.createElement('img');
	cacheImage.src = "img/send_over.gif";
	cache.push(cacheImage);

	$('#nr').keyup(function() {
		if (validateNr2(document.getElementById('nr').value)){
			$("#submit1").attr("src","img/send_over.gif");
		} else {
			$("#submit1").attr("src","img/send.gif");
		}
	});


	$("#coverContent").css({ "left": ($("#leftContent").offset().left + "px"), "top":($("#leftContent").offset().top + "px")});
	$("#coverContent").width($("#leftContent").width());
	$("#coverContent").height($("#leftContent").height());
	$("#coverContent").css('opacity',0.9);
	$("#coverContent").hide();
	
	$("#leftContent").height("60px");
	$("#mainRight").height("60px");
});

/* Miscellaneous functions */
function toTerms(){
	if (locked){
		return false;
	}
	locked = true;
	if (!validateNr(document.getElementById('nr').value)){
		return false;
	}
	// Fixa steg1 färdigt
	$("#leftContent").animate({ height: free_height+"px" }, 700);
	$(steg1).addClass("s1_done");

	// Rensa divven
	removeContents(div_i);

	// Header 1
	$(h2).text("För att använda Call40 måste du acceptera våra användarvillkor");
	
	// Header 3
	$(h3).text("call40 användarvillkor");

	// Link
	$(a1).attr("href", "#");
	$(a1).text("Jag har läst och accepterar Call40’s användarvillkor");
	$(a1).unbind();
	$(a1).click(function() {sendToNr();return false;});
	
	// Man måste kunna avbryta
	$(diven).click(function() {removeDivs();});
	
	$(div_2).append(a1);
	$(div_i).append(imga);
	$(div_i).append(h2);
	$(div_i).append(div_2);
	$(div_i).append(h3);
	$(div_i).append(imga);
	$(body).append(div_i);
	$(body).append(diven);

	$(diven).show();
	$(div_i).show();
	$(diven).fadeTo("normal", 0.4);
	$(div_i).fadeTo("normal", 1);
	window.setTimeout("fetch('anvandarvillkor.txt')",5);
	return false;
}

function sendToNr() {
	// Cleanup
	removeContents(div_i);
	
	// Graphics
	$(h1).text("Skickar programvaran till " + document.getElementById('nr').value);
	$(div_i).append(h1);
	$(div_i).append(imga);
	$.ajax({
		type: "GET",
		url: "recieve_nr/?nr=" + document.getElementById('nr').value + "&sess=" + document.getElementById('somethingsomethingdarkside').value,
		success: function(msg){
			if (msg == "ok"){
				error2("Programmet har skickats","Följ instruktionerna i det sms som skickats till din telefon. Det kan dröja någon minut innan smset kommit fram.","img/sendsms.gif",true);
				// Fixa steg2 färdigt
				$(steg2).addClass("s2_done");
				$('#submit1').attr('disabled', 'disabled');
			} else {
				error("Ett fel uppstod",msg);
			}
		}
	});
}

function fetch(url) {
	$.ajax({
		type: "GET",
		url: url,
		success: function(msg){
			//$(imga).remove();
			div_i.removeChild(imga);
			// Textarea
			$(txt1).text(msg);
			$(divaa).append(txt1);
			$(div_i).append(divaa);
		}
	});
}


/* Helper functions */
function error(title,info){
	error2(title,info,"undefined",false);
}
function error2(title,info,img){
	error2(title,info,img,false);
}

function error2(title,info,img,scrollAfter){
	$(diven).show();
	$(div_i).show();
	$(diven).fadeTo("normal", 0.4);
	$(div_i).fadeTo("normal", 1);
	removeContents(div_i);

	var h1 = document.createElement("H1");
	$(h1).append(document.createTextNode(title));
	var p1 = document.createElement("P");
	$(p1).append(document.createTextNode(info));
	
	if (scrollAfter){
		$(diven).click(function() {
			removeDivs();
			$('html, body').animate(
				{scrollTop: $("#mainRight").offset().top},
				1000
			);
		});
		$(div_i).click(function() {
			removeDivs();
			$('html, body').animate(
				{scrollTop: $("#mainRight").offset().top},
				1000
			);
		});
	} else {
		$(diven).click(function() {removeDivs();});
		$(div_i).click(function() {removeDivs();});
	}

	$(div_i).append(img_close);
	$(div_i).append(h1);
	$(div_i).append(p1);

	if (img != "undefined"){
		var img2 = document.createElement("IMG");
		$(img2).attr("src",img);
		div_i.appendChild(img2);
	}
}
function error3(html){
	$(diven).show();
	$(div_i).show();
	$(diven).fadeTo("normal", 0.4);
	$(div_i).fadeTo("normal", 1);
	removeContents(div_i);
	$(div_i).html(html);
	$(diven).click(function() {removeDivs();});
	$(div_i).click(function() {removeDivs();});
}

function validateNr(nr){
	if (nr == "") {
        error("Felaktigt nummer","Du fyllde inte i ett telefonnummer.");
		return false;
    } else if (!(nr.length == 10)) {
        error("Felaktigt nummer","Fel längd på det angivna telefonnumret. Det skall vara 10 siffror, ex: 07XXXXXXXX.");
        return false;
    } else if (isNaN(parseInt(nr))) {
        error("Felaktigt nummer","Telefonnumret får endast innehålla siffror.");
        return false;
    } else if (nr.substring(0,2) != "07"){
	    error("Felaktigt nummer","Telefonnumret måste börja med \"07\".");
        return false;
	}
    for (var i = 0; i < nr.length; i++) {   
        var c = nr.charAt(i);
        if (((c < "0") || (c > "9"))){
			error("Felaktigt nummer","Telefonnumret får endast innehålla siffror.");
			return false;
		}
    }
    return true;
}
function validateNr2(nr){
	if (nr == "") {
		return false;
    } else if (!(nr.length == 10)) {
        return false;
    } else if (isNaN(parseInt(nr))) {
        return false;
    } else if (nr.substring(0,2) != "07"){
        return false;
	}
    for (var i = 0; i < nr.length; i++) {   
        var c = nr.charAt(i);
        if (((c < "0") || (c > "9"))){
			return false;
		}
    }
    return true;
}

function removeDivs(){
	$(diven).unbind();
	$(div_i).unbind();
	$(diven).fadeTo("fast", 0,function() {$(diven).hide();});
	$(div_i).fadeTo("fast", 0,function() {$(div_i).hide();locked = false;});
}

function validateRef(ref){
	ref = $.trim(ref);
	$.ajax({
		url: "php/is_refID/",
		data: { 'ref' : ref },
		success: function(msg){
			if (ref != "")
				$("#formCheck2").css('visibility','visible');
			else 
				$("#formCheck2").css('visibility','hidden');
			if (msg == true){
				$("#formCheck2").attr("src", "img/checked.gif");
				$("#formCheck3").css('visibility','visible');				
				if (!validateEmails(document.getElementById('input3').value)){
					$("#formCheck3").attr("src", "img/error.gif");
					$("#input3").focus();
				} else {
					$("#formCheck3").attr("src", "img/checked.gif");
					$('#submit2').attr('disabled', 'disabled');
					$('#input1').attr("disabled", true); 
					$('#input2').attr("disabled", true); 
					$('#input3').attr("disabled", true);
					$('#input1').css("color", "#333"); 
					$('#input2').css("color", "#333"); 
					$('#input3').css("color", "#333"); 
					// Send mails
					var name = $.trim($("#input1").val());
					var emails = $.trim($("#input3").val());
					$.ajax({
						url: "tip_validate/",
						data: {
							'name' : name,
							'ref' : ref, 
							'emails' : emails
						},
						success: function(msg){
							if (msg){
								$('#pInput4').html("Epost har skickats ut till dina vänner. Du kan se hur många gratis uppdateringar du har i programvaran innan betalningssteget när du väljer Lägg till operatörsinfo.");
							} else {
								alert("Ett fel uppstod, kontrollera uppgifterna eller kontakta support.");
							}
						}
					});
				}
				return false;
			} else {
				$("#input2").focus();
				$("#formCheck2").attr("src", "img/error.gif");
				return false;
			}
		}
	});
}

function validateName(name){
	if (name == "" || name.indexOf("@") != -1){
		return false;
	}
	return true;
}

function validateEmails(emails){
	var lines = emails.split('\n');
	var count = 0;
	for(i=0;i<lines.length;i++) {
		if (!isValidEmail($.trim(lines[i]))){
			if ($.trim(lines[i]) != "")
				return false;
		} else
			count++;
	}
	if (count > 0)
		return true;
	return false;
}

function isValidEmail(str) {
   return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////OLD/////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////



function showhide(layer_ref) {
	var thediv = document.getElementById(layer_ref);
	if (thediv.clientHeight == 33){
		if (document.all)
			thediv.style.height = 'auto'; 
		else
			thediv.setAttribute("style","height:auto");
	} else {
		if (document.all)
			thediv.style.height = '33px'; 
		else
			thediv.setAttribute("style","height:33px;overflow:hidden");
	}
} 

function setToDoneOrNot(li_ref){
	var theLi = $("#"+li_ref).attr('class');
	if (theLi.indexOf("done") == -1){
		$("#"+li_ref).removeClass();
		$("#"+li_ref).addClass((theLi + "_done"));
	} else {
		$("#"+li_ref).removeClass();
		$("#"+li_ref).addClass(theLi.substring(0, theLi.indexOf("_done")));
	}
}
