$(document).ready(function(){
    //show progress when generate pdf
    $('.generatePdf').click(function(){
        $('.pdfProgress').show();
    });
    
    //create history back link
    $('.goBack').click(function(){
        history.back();
    });
	if($('#nav ul>li.selected').length <= 0){
		$('#nav ul>li:first').addClass('selected');
	}
	$('#main div.sitePath span span:nth-child(n+3)').addClass('on');

    /*
    if($('#top .serviceNav ul:last li').length <= 0){
		$('#top .serviceNav div.navSplit').addClass('skip');
	}
	*/
	
    /* Temp Disabled */
    /*
	$.sifr({
		path: '/Style%20Library/VELUX/Includes/',
		font: 'VeluxGothic', 
		save: true
	});
	$('.spot h1, .spot h2, div.teaser h2').sifr({  });
	*/
	
    $('#content .spot>ul>li.hasPopUpLinks>a').toggle(
      function () {
         $(this).parent('li').addClass('on');
      },
      function () {
        $(this).parent('li').removeClass('on');
      }
    );
	
	
	$('a.buttonBack').attr('href','javascript:history.back(-1);');
	
	$('#main a.printButton').attr('href','javascript:window.print();');
	
	$('#main .sitePath a.contact').attr('href','#');
	$('#main .sitePath a.contact').click(function () {
	  var sender = $(this);
	  $('#main .sitePath div.recBox').slideToggle('fast', function(){
	    if ($(this).is(":visible"))
	    {
	        trackIconEvent(sender, "sendRecommendation");
	    }
	  });
    });
    
    $('#main .sitePath div.recBox a.addRecipient').click(function () {
    	var email = $(this).parent().find('input').attr('value');
    	var $error = $(this).next('div.error');
    	if(valEmail(email))addRecipient($(this));
    });
    
    $('#main .sitePath div.recBox input.valEmail').blur(function () {
    	doInputField($(this));	
    });
    
    
	$('#main .sitePath div.recBox div.submit input').click(function () {
		$('#main .sitePath div.recBox input.valEmail').each(function () {
	    	myState = doInputField($(this));
	    });
	    return myState;
	    //$('#main .sitePath div.recBox textarea').attr('value',$('#main .sitePath div.recBox input').eq(0).attr('value'));
    });
	
    	
	$('#main .faqList dt').click(function () {
	  var faqId = $(this).attr("faqId");
	  $(this).next().slideToggle('fast', function () {
	    if ($(this).is(":visible"))
	    {
	        if (faqId == 0)
	        {
	            return;
	        }

	        var urlToTrack = window.location.href + "?faqitem=" + faqId + "&faq=click";

            try
            {
	            dcsMultiTrack("DCS.dcsuri", urlToTrack, "WT.ti", "FAQ View of item " + faqId);
	        }
	        catch(e) {}
	    }
	  });
    });
     
     $('#main .flashObject').each(function () {
    	  $(this).flash(
    	    { 
    	      src: $(this).find('.SWFFile').attr('href'),
    	      width: $(this).find('.SWFWidth').html(),
    	      height: $(this).find('.SWFHeight').html(),
    	      wmode: 'transparent',
    	      flashvars: { url1: $(this).find('.XMLFile').attr('href') }
    	    },
    	    { version: 8 }
    	);
    });    
    
    $('#main .teaserSpotFlash').each(function() {
        $(this).flash({
            src: $(this).attr('flashURL'),
            width: $(this).attr('flashWidth'),
            height: $(this).attr('flashHeight'),
            wmode: 'transparent'
        });
    });
	
    $('#content .pgThumbs .thumb').click(function(){
		showGalleryItem($(this));
    });
    $('#content .pgThumbs .thumb').hover(
    	function () {
         $(this).addClass('over');
      },
      function () {
        $(this).removeClass('over');
      }

    );
    $('iframe').parent('.ms-WPBody').css('overflow','hidden');
    
    $('#main table.customLayoutGrey > tr:nth-child(even), #main table.customLayoutGrey tbody > tr:nth-child(even), #main table.customLayoutBlue > tr:nth-child(even), #main table.customLayoutBlue tbody > tr:nth-child(even), #main table.customLayoutPurple > tr:nth-child(even), #main table.customLayoutPurple tbody > tr:nth-child(even)').addClass('odd');
    //$('#main table.customLayoutGrey > tr:first-child, #main table.customLayoutGrey tbody > tr:first-child, #main table.customLayoutBlue > tr:first-child, #main table.customLayoutBlue tbody > tr:first-child, #main table.customLayoutPurple > tr:first-child, #main table.customLayoutPurple tbody > tr:first-child').addClass('th');

    $('#main .sitePath a.printButton').click(function(){
        trackIconEvent($(this), "print");
    });
    
    $('#main .sitePath a.generatePdf').attr('href','#');
    $('#main .sitePath a.generatePdf').click(function(){
		if (isPdfGenerating)
		{
			return;
		}
		
		$('.pdfProgress').show();
        var currentUrl = window.location.href;
        var bookmarkIndex = currentUrl.indexOf("#");
        if (bookmarkIndex > -1){
            currentUrl = currentUrl.substring(0, bookmarkIndex);
        }

        var separator = currentUrl.indexOf("?") == -1 ? "?" : "&";
		isPdfGenerating = true;
		setTimeout("updatePdfGenerationState('" + currentUrl + "')", pdfTimeout);
        window.location.href = currentUrl + separator + "printPdf=1";

        trackIconEvent($(this), "pdf")
    });
});

var isPdfGenerating = false;
var pdfTimeout = 3000;

function updatePdfGenerationState(pdfUrl){
	$.ajax({
		type: "POST",
		url: "/_vti_bin/velux/PdfGenerationState.asmx/IsPdfGenerated",
		data: '{"url":"' + pdfUrl + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function(msg) {
			if (msg == true || msg == "true"){
				isPdfGenerating = false;
				$('.pdfProgress').hide();
			}
			else{
				setTimeout("updatePdfGenerationState('" + pdfUrl + "')", pdfTimeout);
			}
		},
		error: function(req, status, error) {
				isPdfGenerating = false;
				$('.pdfProgress').hide();
		}
	});
}

function doInputField($input){
	var $recBox = $('#main .sitePath div.recBox');
	var email = $input.attr('value');
	var index = $('#main .sitePath div.recBox input.valEmail').index($input);
	
	var $error = $recBox.find('div.error').eq(index);
	
	if(valEmail(email)){
		$error.addClass('skip');
		if(index > 0)addRecipientMail(email);
		return true;
	}
	else{
		$error.removeClass('skip');
		return false;
	}
}

function addRecipient($recipient){
	$recipientLine = $recipient.parent().clone();
   	$recipient.parent().find('input').attr({value: ''});
   	
   	$recipientLine.find('input').attr({disabled: 'disabled'});
   	$recipientLine.find('a.addRecipient').attr('class','clearRecipient').click(function () {
    	clearRecipient($(this));
    	
    });
   	$recipient.parent().before($recipientLine);
}

function clearRecipient($recipient){
	$recipient.parent().remove();
	delRecipientMail($recipient.parent().find('input').attr('value'));
   	
}

function addRecipientMail(mail){
	$recipients = $('#main .sitePath div.recBox input').eq(0);
	currentRecipients = $recipients.attr('value');
	
	if(currentRecipients.indexOf(mail) == -1){
		currentRecipients += mail + ';'
		$recipients.attr('value',currentRecipients);
	}
}

function delRecipientMail(mail){
	$recipients = $('#main .sitePath div.recBox input').eq(0);
	currentRecipients = $recipients.attr('value');
	
	currentRecipients = currentRecipients.replace(mail + ';','')
	$recipients.attr('value',currentRecipients);
}

function showGalleryItem($item){

	var $thumbs = $('#content .pgThumbs');
	var $index = $thumbs.find('.thumb').index($item);
	
	var $img = $('#content .photoGallery img.pgView');
	var $desc = $('#content div.pgHTML');
	var $data = $('#content div.pgData>div');
	
	$item.siblings('.on').removeClass('on');
	$item.addClass('on');
	
	$img.attr({src:$item.find('img').attr('longdesc'),alt:$item.find('img').attr('alt')});
	$desc.html($data.eq($index).html());
}

function valEmail(email){	
	var pattern=/^([a-åA-å0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    return pattern.test(email);
}

try{
	document.execCommand('BackgroundImageCache', false, true);
}
catch(e){}

function trackIconEvent(sender, iconName)
{
    var pageUrl = sender.attr("pageUrl");
    var pageTitle = sender.attr("pageTitle");

    if (typeof(pageUrl) == 'undefined' || typeof(pageTitle) == 'undefined')
    {
        return;
    }

    var separator = pageUrl.indexOf("?") == -1 ? "?" : "&";
    var urlToTrack = pageUrl + separator + "icon=" + iconName;

    try
    {
        dcsMultiTrack("DCS.dcsuri", urlToTrack, "WT.ti", pageTitle);
    }
    catch(e){}
}
