//--------------------------------------------------------------------
// global variables
//--------------------------------------------------------------------

var topSearchText
$("html").addClass("JS")
//--------------------------------------------------------------------
// fires when the DOM is ready
//--------------------------------------------------------------------

$(document).ready(function() {
	navHover();
	topSearch();
	extWindows();
	closeX();
	markAllText();
	popAForm();
	analyseThis();
	indexVideos();
	prettyLinkButton()
});

//--------------------------------------------------------------------
// useful functions
//--------------------------------------------------------------------

// navHover() makes fancy mousovers on left navigation and newslisting on startpage
function navHover() {
	$(".nav").css("height",$(".nav").parent().height())
	$(".indexNews, .nav").children("ul").children("li").mouseover(function(){
		$(this).addClass("paHover");
	});
	$(".indexNews ,.nav").children("ul").children("li").mouseout(function(){
		$(this).removeClass("paHover");
	});
}

// topSearch() takes the label and puts it into the searchfield and hides it on focus
function topSearch(){
	$(".topSearch").css("display","none");
	topSearchText = $(".topSearch label").text();
	$(".topSearch :text").val(topSearchText);
	$(".topSearch label").hide();
	$(".topSearch :text").focus(function(){
		if($(this).val() == topSearchText){
			$(this).val("");
		}
	});
	$(".topSearch :text").blur(function(){
		if($(this).val() == ""){
			$(this).val(topSearchText);
		}
	});
	
	$(".topSearch").css("display","block");
}

// extWindows() makes links open in a different window. use rel="external" instead of target="_blank" and rel="popup" or rel="popup|[width]|[height]" for popups
function extWindows(){
	$("a[rel*=external]").attr("target","_blank");
	$("a[rel^=popup]").click(function(){
		theHref = $(this).attr("href");
//		$(this).attr("href","javascript:void(0)");
		var popupWidth, popupHeight
		var relSplit = $(this).attr("rel").split("|");
		if(relSplit[1]){
			popupWidth = relSplit[1];
			popupHeight = relSplit[2];
		} else {
			popupWidth = 435;
			popupHeight = 350;
		}
		popMeUp(theHref,popupWidth,popupHeight)
		return false;
	});
	
}
function popMeUp(strURL, strWidth, strHeight) {
    theWin = window.open(strURL, "popupWin", "scrollbars,resizable,height=" + strHeight + ",width=" + strWidth);
    theWin.focus();
}
// Puts display:none on the div when the X-button is clicked
function closeX(){
    $(".welcomePopup img").click(function(){
        $(".welcomePopup").hide();
    });
}

function doSearch(e){
    if(window.event && window.event.keyCode == 13 || e && e.keyCode == 13){
        document.getElementById('ctl00_ctl04_BtnQuickSearch').click();
        return false;
        }
        
    return true;
   }
   
function markAllText() {
	$(".inputArea4Code, .inputArea4Link").click(function() {
		$(this).select();
	});
}

// popupformulär
// popAForm() makes forms popup in the middle of the page use rel=popForm|small/medium/large
var popAFormIsSubmitting = false;
function popAForm() {
    $("a[rel*='popForm']").click(function(e){
        e.preventDefault();
        scrollTop = $(window).scrollTop();
        var theRel = $(this).attr("rel")
        if((/small/).test(theRel)){
            theformClass = "popupSmall";
        } else if((/large/).test(theRel)){
            theformClass = "popupLarge";
        } else {
            theformClass = "popupMedium";
        }
        
        theHref = $(this).attr("href");
        $("body").append('<div class="popupBg"></div>');
        $("body").append('<form action="' + theHref + '" method="post" class="' + theformClass + '"><div class="popupTop"></div><div class="popupBody"></div><img src="/UI/Images/ecommerce/pop.close.png" class="popupClose"/><div class="popupBottom"></div></form>');
        theLeft = (($(window).width() / 2) - ($("." + theformClass).width() / 2)) + "px";
        theTop = ($("." + theformClass).height()>($(window).height()-20))?(10 + scrollTop) + "px":(($(window).height() / 2) - ($("." + theformClass).height() / 2) + scrollTop) + "px";
        $("." + theformClass).css({
            display:"none",
            left:theLeft 
        });
        $(".popupBody").load(theHref + " .companyContent","",function(){
        	checkIfTabs()
            theTop = ($("." + theformClass).height()>($(window).height()-20))?(10 + scrollTop) + "px":(($(window).height() / 2) - ($("." + theformClass).height() / 2) + scrollTop) + "px"
            $("." + theformClass).css({ 
                display:"block",
                top:theTop 
            });
            
            
            
        });
        $("form." + theformClass).submit(function(e){
            e.preventDefault();
            if(popAFormIsSubmitting)
                return false;
            popAFormIsSubmitting=true;    
            if(($("#conFirmMe").size() > 0) && ($("#conFirmMe").attr("checked") != true)) 
            {
                popAFormIsSubmitting=false;    
                return false;
            }
            formData = $("form").serialize();
            $.post(theHref, formData, function(data) {
	            $(".popupBody").html($(data).find(".companyContent").html())
                checkIfTabs();
                popAFormIsSubmitting=false;
            });
            $("html,body").animate({scrollTop: $(".popupBody").offset().top-5},500);
            

        });
        $(".popupClose,.popupCloseText").click(function(){
            $(".popupBg").remove();
            $("." + theformClass).remove();
        });
        return false;
    });
}

var theFieldSet = 0

function checkIfTabs(){
	var domain='.com';
	var arrPrevNext = new Array(2);
	if(document.location.host.lastIndexOf('.')!=-1)
		domain = document.location.host.substr(document.location.host.lastIndexOf('.')).toLowerCase();
	switch(domain)
	{
		case ".de":
			arrPrevNext= new Array("Zur&uuml;ck","Weiter");
		break;
		default:
			arrPrevNext = new Array("Previous step","Next step");
	}
	
	
	if($(".popupBody fieldset").length > 1){
		$(".popupBody fieldset:first").before('<ul class="fieldNav"></ul>')
		
		$(".popupBody fieldset").each(function(){
			$(".fieldNav").append('<li>' + $(this).attr("title") + '</li>')
			$(this).hide()
		})
		var zindex = 5
		$(".fieldNav li").each(function(){
		    $(this).css("zIndex",zindex);
		    zindex--;
		})
		$(".popupBody ul.fieldNav li").each(function(i){
			var i=i
	        $(".popupCloseText").click(function(){
                $(".popupBg").remove();
                $("." + theformClass).remove();
            });
 			if(i < ($("ul.fieldNav li").size()-1)){
					$(".popupBody fieldset:eq("+i+")").append('<p class="floatRight"><a class="button" href="javascript:goFieldSet(' + (i + 1) + ',' + i + ')">' + arrPrevNext[1] + '</a></p>')
			}/* else {
			    $(".popupBody fieldset:eq("+i+")").append('<p><input type="checkbox" id="conFirmMe"> I Agree with the terms</p>');
				$(".popupBody fieldset:eq("+i+")").append('<p class="floatRight"><button class="submit" type="submit">Skicka</button></p>');
			}*/
			if(i>0){
					$(".popupBody fieldset:eq("+i+")").append('<p class="floatRight"><a class="buttonPrev" href="javascript:goFieldSet(' + (i - 1) + ',-1)">' + arrPrevNext[0] + '</a></p>')

			}
			$(this).click(function(){
				goFieldSet(i,theFieldSet);
				theFieldSet = i
			})
			
		});
		$(".popupBody fieldset:first").show()
		$(".popupBody ul.fieldNav li:first").addClass("active")
		$(".popupBody fieldset:last legend").after('<div id="theSubMitString"></div>')
	    $("#Country").change(function(){
            if($(this).val() == "SE"){          
                $("#OrgNumber").removeAttr("disabled")
                $("#OrgNumber").parents("p").removeClass("disabled")
                $("#Vat").attr("disabled",true)
                $("#Vat").parents("p").addClass("disabled")
            } else {  
                $("#Vat").removeAttr("disabled")
                $("#Vat").parents("p").removeClass("disabled")
                $("#OrgNumber").attr("disabled",true)
                $("#OrgNumber").parents("p").addClass("disabled")
           }   
        })

	    $("#Vat").blur(function(){
	        checkVat();
	    })
	    ;
	    
		
	}

}
function validatePopForm(){
    
    alert($(this).parent().tagName)
}
    
var theSubmitString
function filloutBlanks() {
	theSubmitString ="";
	$(".popupBody label").each(function(){
		var theName = $(".inputName",this).text();
		var theValue = $(this).next().val();
		var theInputName = $(this).next().get()[0].name;
		
		if(jQuery.trim(theValue)==""){
			theSubmitString += '<p><span class="label">' + theName + '</span>&mdash;</p>';
		} 
		else {
		    
		    switch(theInputName)
		    {
		        case "Industry": // id|name
		            if(theValue.indexOf("|") != -1)
		                theValue= theValue.split("|")[1];
		        default:
			        theSubmitString += '<p><span class="label">' + theName + '</span>' + theValue + '</p>';
			}
		}
	})
	
	$("div.inputP").html(theSubmitString)
}


function checkVat(){
    theVat = $("#Vat");
    if ($.trim(theVat.val()) != ""){
        theVatString = $("#Country").val() + "/" + $("#Vat").val().replace(/\D/g, ""); 
        $.getJSON('http://isvat.appspot.com/' + theVatString + '/?callback=?', function(data){
          
            if(!data && !data.error){
                theVat.parents("p").addClass("error")
                theVat.parents("p").find(".validation").hide()
                theVat.parents("p").find(".validationSpecial").css("display","block")
            } else {
                
                theVat.parents("p").removeClass("error");
                theVat.parents("p").find(".validation").hide()
                theVat.parents("p").find(".validationSpecial").hide()
            }
        });
    }
}

function goFieldSet(i,theField){
  //  alert(theField)
    var returnValue = "true";
    var mailPattern = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    var orgnrPattern = /^((\d{6,6})-?(\d{4,4}))?$/;
    $(".popupBody fieldset:eq(" + theField + ")").find(":input").each(function(){
        if((($(this).val() == "")||($(this).val() == -1))&&(!$(this).hasClass("tentative"))){
            $(this).parents("p").addClass("error")
            $(this).parents("p").find(".validation").css("display","block")
            returnValue = "false"
        } else if(($(this).attr("id") == "Email")  && (mailPattern).test($(this).val()) == false ) {
            $(this).parents("p").addClass("error")
            $(this).parents("p").find(".validation").hide()
            $(this).parents("p").find(".validationSpecial").css("display","block")
            returnValue = "false"
        } else if(($(this).attr("id") == "OrgNumber")  && (orgnrPattern).test($(this).val()) == false ) {
            $(this).parents("p").addClass("error")
            $(this).parents("p").find(".validation").hide()
            $(this).parents("p").find(".validationSpecial").css("display","block")
            returnValue = "false"
        } else {
            $(this).parents("p").removeClass("error");
            $(this).parents("p").find(".validation").hide()
            $(this).parents("p").find(".validationSpecial").hide()
           
        }
    })
    if(returnValue == "true"){
       // alert($(this).val())
        theField = i
        $(".popupBody fieldset").hide();
        $(".popupBody fieldset:eq("+i+")").show();
        $(".popupBody ul.fieldNav li").removeClass("active")
        $(".popupBody ul.fieldNav li:eq("+i+")").addClass("active")
        filloutBlanks()
        $("html,body").animate({scrollTop: $(".popupBody").offset().top-5},500);
    }
}
function testMail(){
    var mailPattern = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    $(this).parents(".part").find("textarea,:text").each(function(){
        theLabel = $("label[for=" + $(this).attr("id") + "]");
        if($(this).val() == theLabel.text() || $.trim($(this).val()) == "" ){
            $(this).addClass("error");
            returnVal = false ;
        } else if($(this).hasClass("email") && (mailPattern).test($(this).val()) == false){
            $(this).addClass("error");
            returnVal = false ;
        }
    });
}

function analyseThis() {
    //print
    $("li.print a").click(function() {
        pageTracker._trackEvent("Activity", "Print");
    });
    //email
    $(".mailForm :submit").click(function() {
        pageTracker._trackEvent("Activity", "Email");
    });
    $("a.email").click(function() {
        pageTracker._trackEvent("Activity", "EmailsToCompany");
    });
    //shareThis
    $("a.stbutton").click(function() {
        pageTracker._trackEvent("Activity", "Share");
    });
    //external links
    $("div.vcard .url").click(function() {
        pageTracker._trackEvent("Activity", "VisitsToSite");
    });
    //file download
    $(".docs a").click(function() {
        pageTracker._trackEvent("Download", "File", $(this).attr("class"));
    });
    //image download
    $(".downloadImage").click(function() {
        pageTracker._trackEvent("Download", "Image", $(this).attr("title"));
    });
}

var theVideoLength;
var theVideoNum;
var nextVideoNum;
function indexVideos(){
    var theVideoList = $("ul.videoSlides");
    theVideoLength = $("li",theVideoList).size();
    var theVideoHeight = 0;
    $("li",theVideoList).each(function(){
        if($(this).height() > theVideoHeight)
            theVideoHeight = $(this).height();
        $(this).hide();
        $("a.relA",this).css({
            height:"83px",
            overflow:"hidden"
        })
//$(".snapShot img",this).css({
//    clip:"rect(0,100%,83px,0)"
    
//})

        $(this).css({
            position:"absolute",
            top:0,
            left:0,
            width:"100%"
        })
    });
    
    theVideoList.css({
        height:(theVideoHeight + 20) + "px",
        position:"relative"
    });
    
    $("li:first",theVideoList).show();
    
    
    
    theVideoNum = 0;
    nextVideoNum = 0;
    setTimeout('runVideos()',3000);
    
}
function runVideos(){
    if(theVideoNum < (theVideoLength-1)) {
        nextVideoNum ++;
    } else {
        nextVideoNum = 0;
    }
    $("ul.videoSlides li:eq(" + theVideoNum + ")").fadeOut();
    $("ul.videoSlides li:eq(" + nextVideoNum + ")").fadeIn();
    theVideoNum = nextVideoNum;
    setTimeout('runVideos()',3000);
    
}
function prettyLinkButton(){
    $(".eCommerce .article a>span").parent().css("textDecoration", "none");
}

function searchError(message)
{
    $(document).ready(function()
        {
            alert(message);
        }
        );
}