function pageLoad(sender, args) {
    /* slides debug */
    $('.slide-content.selected').show();
    $('.checkout-pagination a.link-button').click(function() {
        if ($(this).attr('href').length > 1) {
            $('.slide-content').hide();
            $($(this).attr('href')).show();
            return;
        }
    });

    /* checkout process */

    $('.bank-logo').each(function() {
        jQuery("<img>").attr("src", $(this).attr('src').replace('.jpg', '-hover.jpg'));
    });

    $('.bank-logo').hover(function() {
        var t = $(this);
        t.attr('src', t.attr('src').replace('.jpg', '-hover.jpg'));
    }, function() {
        var t = $(this);
        t.attr('src', t.attr('src').replace('-hover', ''));
    });

    /* accordion */
    $('div.accordion-title').live("click", function(e) {
        if ($(this).parent().hasClass('selected')) return;
        $('div.accordion-content').slideUp('normal').parent('.accordion').removeClass('selected');
        $(this).next().slideDown('normal').parent('.accordion').addClass('selected');
    });

    /* tabbed content */
    $('.tabs.pink .selected a').each(function() {
        $($(this).attr('hash')).show();
    });
    $('.tabs.pink a').click(function() {
        if ($(this).parent().hasClass('selected')) return;
        $('.tab-content').hide();
        $('.tabs li').removeClass('selected');
        $($(this).attr('hash')).show();
        $(this).parent().addClass('selected');
        return false;
    });

    /* init gallerific */

    if ($('#thumbs ul li').length > 0) {
        var onMouseOutOpacity = 0.67;
        $('#thumbs ul.thumbs li').opacityrollover({
            mouseOutOpacity: onMouseOutOpacity,
            mouseOverOpacity: 1.0,
            fadeSpeed: 'fast',
            exemptionSelector: '.selected'
        }).click(function() {
            $('#gallery').show();
            $('.product-details').hide();
            return false;
        });

        $('.close-gallery').click(function() {
            $('#gallery').hide();
            $('.product-details').show();
            return false;
        });

        var gallery = $('#thumbs').galleriffic({
            delay: 2500,
            numThumbs: 15,
            preloadAhead: 10,
            enableTopPager: true,
            enableBottomPager: true,
            maxPagesToShow: 7,
            imageContainerSel: '#slideshow',
            controlsContainerSel: '#controls',
            captionContainerSel: '#caption',
            loadingContainerSel: '#loading',
            renderSSControls: false,
            renderNavControls: true,
            playLinkText: 'Play Slideshow',
            pauseLinkText: 'Pause Slideshow',
            prevLinkText: 'Edellinen',
            nextLinkText: 'Seuraava',
            nextPageLinkText: 'Seuraava &rsaquo;',
            prevPageLinkText: '&lsaquo; Edellinen',
            enableHistory: false,
            autoStart: false,
            syncTransitions: true,
            defaultTransitionDuration: 900,
            onSlideChange: function(prevIndex, nextIndex) {
                // 'this' refers to the gallery, which is an extension of $('#thumbs')
                this.find('ul.thumbs').children()
					.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
					.eq(nextIndex).fadeTo('fast', 1.0);
            },
            onPageTransitionOut: function(callback) {
                this.fadeTo('fast', 0.0, callback);
            },
            onPageTransitionIn: function() {
                this.fadeTo('fast', 1.0);
            }
        });
    }
    /* editmode select list */
    $('button[_move]').click(function() {
        var move = $(this).attr('_move');
        var tt = $(this).attr('_target');
        $('.' + tt + ' option:selected').each(function() {
            switch (move) {
                case 'up':
                    $(this).insertBefore($(this).prev());
                    break;
                case 'down':
                    $(this).insertAfter($(this).next());
                    break;
            }
        }).parent().focus();
        return false;
    });


    /* Campaign search */
    $('.equalWidth').keypress(function(e) {
        if (e.keyCode == 13) {
            $('.button-go').click();
        }
    });

    /* Google Analytics & Snoobi statistics */
    $('.link-facebook').click(function() {
        try {
            var url = 'WebShop/Facebook/' + $.getUrlVar('t');
            snoobi.trackPageView(url);
            pageTracker._trackPageview(url);
        } catch (err) { }

    });
    
    //GA
    if($.getUrlVar(true, 'SWEPostnRowId') != null){    
        //http://code.google.com/intl/fi-FI/apis/analytics/docs/tracking/gaTrackingSite.html
            
        try {        
            //Get Total from bundle
            var price = $.getTotalPrice();
            var tax = $.getTax(price);
            
            //Begin Trans
            _gaq.push(['_addTrans', getGAID(), 'DNA Verkkokauppa', price, tax, '', '', '', 'FI']);

            //Mobile
            pushGAItem(getGAID(), $.getUrlVar(true, 'Slot1'));
             //Subscription
            pushGAItem(getGAID(), $.getUrlVar(true, 'Slot2'));
            //Commit
            _gaq.push(['_trackTrans']);
        
        } catch (err) { }        
        
    }     
    
    /* SMS */
        
    $('.link-sendSMS').click(function() {
        var url=window.location.href.split('/'); 
        url.length=3;
        url = url.join('/')+ '/_layouts/Dna.DnaOy/WebShopSendPageUrlToSMS.aspx';  
          
        url = url + '?ProductDisplayName=' + encodeURI($('#smsProductDisplayName').text());
        url = url + '&ProductPrice=' + encodeURI($('#smsProductPrice').text());         
          
        var $dialog =    
            jQuery.FrameDialog.create({       
            url: url,       
            width: 570,
            height: 330,    
            autoOpen: false,
            buttons: {},
            title: $('#modalDialogTitle').text(),
            closeText: $('#modalDialogClose').text()
        });    
            
        $dialog.dialog('open');
        
        return false;        
    });
    
    /* Coverage Search WP */
    $('.coverageSearchBtn').click(function(e) {
        
        var address = $('.fieldAddress').val();
        var town = $('.fieldTown').val();
        
        var servicePattern = $('.servicePattern').text();
        var serviceUrl = $('.serviceUrl').text();
        var serviceLevel = $('.serviceLevel').text();
        var serviceLangCode = $('.serviceLangCode').text();
        
        var url = format(servicePattern, serviceUrl, serviceLevel, serviceLangCode, affectoWayToEncode(address), affectoWayToEncode(town));
                  
        var $dialog =    
            jQuery.FrameDialog.create({       
            url: url,       
            width: 950,       
            height: 700,       
            autoOpen: false,
            buttons: {},
            title: $('#modalDialogTitle').text(),
            closeText: $('#modalDialogClose').text()
        });    
            
        $dialog.dialog('open'); 
        
        $.pushGAEvent('Coverage Search','Kuuluvuushaku', address, town);
        
        return false;
    });
    
	$('.coverage-search-field').focus(function () {
		$(this).addClass('focus-on');
	}).blur(function () {
		$(this).removeClass('focus-on');
	});
	    

    /* Webshop modal dialog */
    $('#OpenDialog').click(function() {

        $('#ModalDialog').dialog('open');
        return false;

    });

    $('#ModalDialog').dialog({
        modal: true,
        autoOpen: false,
        height: '250',
        width: '500',
        draggable: true,
        resizeable: true,        
        title: 'M&auml;&auml;r&auml;aikaisen sopimuksen siirt&auml;minen',    
        closeText: 'Sulje'
    });

    /* Print Product Card */	
    $('.product-card a.product-print').click(function() {
        //Remove existing iframePrintArea
        $('#iframePrintArea').remove();
		// Create an iframe and copy details to placeholders with the classname of "fill-in"
		// the ID's of source and destination must match
		// if tagname is IMG, use it's background-image property for source and fill in the src attribute of the destination
        var $iframe = $('<iframe id="iframePrintArea" allowtransparency="true" width="800" height="500" name="iframePrintArea" src="/_layouts/Dna.DnaOy/WebShopPrintProductCard.aspx" />')
			.appendTo('#printArea')
			.load(function(){
			$('.fill-in',$(this).contents()).each(function() {
				var tpl = $('#'+$(this).attr('id'),$(this).closest('html'));
				switch(tpl.attr('tagName')) {
					case "IMG" : 
						var tmp = $('[ID$='+$(this).attr('id')+']').css('background-image').match(/\(([^\)]*)\)/)[1].replace(/(['"])/g, "");
                        var url=tmp.split('/');
                        url.splice(0,3);                                                                        
                        url = "/" + url.join('/');
						$(tpl).attr('src',url);
					break;
					default	:
						$(tpl).html($('#'+$(this).attr('id')).html());
				}
			}).focus();
			$(iframePrintArea.document).attr("title", $('title').html());
			window.frames['iframePrintArea'].focus();
			window.frames['iframePrintArea'].print();
		});     
		return false;     		
    });    
    
}


/* reads Total price from bundle*/
$.extend({
    getTotalPrice: function(){
        var price;    
        var _total = $('.price:eq(2)');   
        price = parseFloat(_total.text().replace(",", "."))                
        if(isNaN(price)){
            price = 0;
        }                
        return price;
    }
});

/* Calc tax based on price*/
$.extend({
    getTax: function(price){
        var tax = 0;
        if(price > 0){
            tax = (price - (1/1.23*price)).toFixed(2);
        }
        return tax;
    }
});

/* reads url parameter or link-facebook href to array */
$.extend({ 

    getUrlVars: function(bUrl) {
        var vars = [], hash;
        var hashes;
                
        if(bUrl){
            hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');      
        } else {
            hashes = $('.link-facebook').attr('href').slice($('.link-facebook').attr('href').indexOf('?') + 1).split('&');
        }
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    },

    getUrlVar: function(bUrl, name) {
        return $.getUrlVars(bUrl)[name];
    }
});    

$.extend({
    postJSON: function(url, data, callback)
    {
        $.post(url, data, callback, "json");
    }
});

function getGAID(){
    if(readCookie("GAID") == null){
        var _gaid = randomString();        
        createCookie("GAID", _gaid, false);   
    }
    return readCookie("GAID");
}

function format(str) {
  for(i = 1; i < arguments.length; i++) {
    str = str.replace('{' + (i - 1) + '}', arguments[i]);
  }
  return str;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function randomString() {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = 25;
	var randomstring = '';
	for (var i=0; i<string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	return randomstring;
}

function affectoWayToEncode(value){
    var retValue = value;
    if(retValue != null){
        retValue = retValue.replace(' ', '%20');
        retValue = retValue.replace('å', '%C3%A5');
        retValue = retValue.replace('ö', '%C3%B6');
        retValue = retValue.replace('ä', '%C3%A4');
        retValue = retValue.replace('Ä', '%C3%84');
        retValue = retValue.replace('Ö', '%C3%96');
        retValue = retValue.replace('Å', '%C3%85');               
    }

    return retValue;
}

/* Generated Google Analytics product info event */
function pushGAItem(gaid, productId){

    $.ajax({
        type: "POST",
        url: "/_layouts/Microsoft.Services.Fi.WebServices/WebShop.asmx/GetProductInfo",
        data: "{ productId: '" + productId + "' }",   
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: 
            function(response) {
                try {
                    var product = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;            
                    if(product.ProductId != null){
                        _gaq.push(['_addItem', gaid, product.ProductId, product.DisplayName, product.ProductType, product.MonthlyPrice, 1]);
                    }                        
                } catch (err) { }       
        },
            failure: function(ex) {
                
        }
            
        });
}

/* Generate Google Analytics Event tracking */
$.extend({
    pushGAEvent: function(category, action, opt_label, opt_value){
        try{
            _gaq.push(['_trackEvent', category, action, opt_label, opt_value]);
        } catch (err) { }
    }
});


function countProperties(obj) {
  var prop;
  var propCount = 0;
  
  for (prop in obj) {
    propCount++;
  }
  return propCount;
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}
