$(document).ready(function () {
    
    $('.png').supersleight({shim: 'img/blank.gif'});

    $('#header').mouseover(function () { if (cartTimer) clearTimeout(cartTimer); });

    initCart();
    initSearch();
    initTinkain();

    $.validator.messages.digits = '';
    $.validator.messages.email = '';
    $.validator.messages.required = '&nbsp;*';

    var bodyId = $('body').attr('id'),
        action = {
            'page-default': initDefault,
            'page-ostoslistaprint': initPrint,
            'page-arvonta': initArvonta
        };
    if (action[bodyId]) action[bodyId]();

    // Load feeds last
    initSyke();
});

$(window).load(function() {
    $('#ohjekupla-container').slideDown('fast');
});

/* Helper function for string formatting */
String.prototype.insert = function ()
{
    var strings = arguments;
    return this.replace(/\{(\d+)\}/g, function (m0, m1) {
    return strings[m1];
    });
};

/* Helper function for loose in array comparison */
Array.prototype.inArray = function (value)
{
    for (var i = 0; i < this.length && this[i] != value; i++);
    return i == this.length ? -1 : i;
};

/* Helper for setting a cookie */
function setCookie (name, value, days)
{
    var cookie = name + "=" + value;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 3600000);
        cookie += "; expires=" + date.toUTCString();
    }
    document.cookie = cookie + "; path=/";
}

/* Helper for getting a cookie value by name */
function getCookie (name)
{
    var pattern = new RegExp(name + '=([^;]+)', 'i'),
        match = document.cookie.match(pattern);

    return match && match[1] || null;
}

/* Helper for tidying urls */
function tidy (url)
{
    return url.replace(/view=|partial=/gi, '').replace(/\?|&/g, '/').replace(/=/g, ':');
}

/* Helper for snoobi and analytics tracking */
function trackView (code)
{
    return;

    snoobi.trackPageView(code);
    pageTracker._trackPageview(code);
}

/* Handle sending forms */
function sendHandler (target, callback, code)
{
    
	return function (form) {
        trackView(code);
        $(form).ajaxSubmit({target: target, success: callback});
    };
}

/* Initialize search */ 
var tarkennettuauki = 0;
var ohjeetauki = 0;
function initSearch ()
{
     
     
     $('#quick-search-form select').change(function (e) {
        $('#quick-search-form').submit();
     });

     $("#avaa-tarkennettu,#avaa-tarkennettu2").click(function (e) {
        e.preventDefault();
        if (tarkennettuauki == 1) {
            $('#paivavalinta').show();
            $('#info-palkki').fadeTo('fast', 1);
            $('#palkki-tarkennettuhaku .palkki-nuoli').hide();
            $('#haku-palkki').show();
            $('#tarkennettu-palkki').hide();
            $("#haku-palkki-laajennettu").slideUp("fast");
            ohjeetauki = 0;
            tarkennettuauki = 0;
        }
        else if (tarkennettuauki == 0) {
            $('#paivavalinta').hide();
            $('#palkki-ohjeet .palkki-nuoli').hide();
            $('#tarkennettu-palkki').show();
            $('#palkki-tarkennettuhaku .palkki-nuoli').show();
            $('#ohjeet-palkki').hide();
            $('#info-palkki').fadeTo('fast', 0);
            $("#haku-palkki-laajennettu").slideDown("fast");
            $("#ohjeet").slideUp("fast");
            ohjeetauki = 0;
            tarkennettuauki = 1;
        }
    });

    $("#avaa-ohjeet,#avaa-ohjeet2").click(function (e) {
        e.preventDefault();
        if (ohjeetauki == 1) {
            $('#paivavalinta').show();
            $('#info-palkki').fadeTo('fast', 1);
            $('#palkki-ohjeet .palkki-nuoli').hide();
            $('#haku-palkki').show();
            $('#ohjeet-palkki').hide();
            $('#tarkennettu-palkki').hide();
            $("#ohjeet").slideUp("fast");
            tarkennettuauki = 0;
            ohjeetauki = 0;
        }
        else if (ohjeetauki == 0) {
            $('#paivavalinta').hide();
            
            $('#palkki-tarkennettuhaku .palkki-nuoli').hide();
            $('#ohjeet-palkki').show();
            $('#palkki-ohjeet .palkki-nuoli').show();
            $('#tarkennettu-palkki').hide();
            $('#info-palkki').fadeTo('fast', 0);
            $("#ohjeet").slideDown("fast");
            $("#haku-palkki-laajennettu").slideUp("fast");
            tarkennettuauki = 0;
            ohjeetauki = 1;
        }
    });

    $("#sulje-tarkennettu").click(function (e) {
        e.preventDefault();
        $('#info-palkki').fadeTo('fast', 1);
        $('#palkki-tarkennettuhaku .palkki-nuoli').hide();
        $('#haku-palkki').show();
        $('#tarkennettu-palkki').hide();
        $("#haku-palkki-laajennettu").slideUp("fast");
    });

    $("#sulje-ohjeet").click(function (e) {
        e.preventDefault();
        $('#info-palkki').fadeTo('fast', 1);
        $('#palkki-ohjeet .palkki-nuoli').hide();
        $('#haku-palkki').show();
        $('#ohjeet-palkki').hide();
        $('#tarkennettu-palkki').hide();

        $("#ohjeet").slideUp("fast");
    });

    $(".pikahaku .seuraava-ohje").click(function (e) {
        e.preventDefault();
        $('#pikahaku-wrapper').hide();
        $('#tarkennettuhaku-wrapper').show();
    });

    $(".tarkennettuhaku .seuraava-ohje").click(function (e) {
        e.preventDefault();
        $('#tarkennettuhaku-wrapper').hide();
        $('#ohjeet-wrapper').show();
    });

    $(".ohjeet .seuraava-ohje").click(function (e) {
        e.preventDefault();
        $('#ohjeet-wrapper').hide();
        $('#kuvasto-wrapper').show();
    });

    $(".ohje-close").click(function (e) {
        e.preventDefault();
        $('#ohjekupla-container').hide();
        setCookie ('ohjeetshowed',1,6);
    });
    $(".kuvasto .seuraava-ohje").click(function (e) {
        e.preventDefault();
        $('#ohjekupla-container').hide();
        setCookie ('ohjeetshowed',1,6);
    });

    var ohjeetshowed = getCookie('ohjeetshowed');

}

/* Helper for setting a cookie */
function setCookie (name, value, days) {

    var cookie = name + "=" + value;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + days * 24 * 3600000);
        cookie += "; expires=" + date.toUTCString();
    }
    document.cookie = cookie + "; path=/";
}

/* Helper for getting a cookie value by name */
function getCookie (name) {
    var pattern = new RegExp(name + '=([^;]+)', 'i'),
        match = document.cookie.match(pattern);

    return match && match[1] || null;
}
    
/* Initialize shopping list */

var cartIndex = 0,
    cartPerPage = 5,
    cartItemWidth = 192,
    cartOpen = false,
    cartRemovedItem = false,
    cartLength,
    cartLimit,
    cartTimer;
    
function scrollToForm ()
{
    $('html,body').scrollable().animate({ scrollTop: 535 }, 400);
}

function initCart (e)
{
    $('#tyhjenna-ostoslista,.poista,.poista-print').live('click', removeCartItem);

    // SHOW AND HIDE EMAILSHARE
    $("#listsharelinkemail").live('click', function (e) {
        e.preventDefault();
        if ($('#emailform-wrapper').hasClass('closed')) {
            $("#emailform-wrapper").slideDown("fast");
            $('#emailform-wrapper').removeClass('closed');
        } else {
            $('#emailform-wrapper').hide();    
            $('#emailform-wrapper').addClass('closed');
        }
    });
    
    //$("#listsharelinkprint").click(function (e) {
    //    e.preventDefault();
    //    window.location = 'ostoslista/print?tf=1';
    //});        
    
    loadCart();
}

function loadCart ()
{
    $('#emailform-wrapper').addClass('closed');

    cartLength = $('#ownlist-slider .pthumbcontent-ostoslista').length;
    cartLimit = Math.max(0, cartLength - cartPerPage);
    cartIndex = Math.min(cartIndex, cartLimit);

    /* Restore previous styles */
    $('#ownlist-slider').css({
        width: cartLength * cartItemWidth,
        left: '-' + cartIndex * cartItemWidth + 'px'
    });
    if (cartOpen) {
        $('#ostoslista').show();
        showCart();
    }

    if (cartLength > cartPerPage) {
        /* Animate to last item */
        if (!cartRemovedItem) {
            cartIndex = cartLimit;
            $('#ownlist-slider').animate({left:'-' + cartIndex * cartItemWidth + 'px'}, 400, function () { $('#nuoli-oikea').hide(); });
        }
        cartRemovedItem = false;

        /* Attach browsing events  */
        $('#nuoli-vasen,#nuoli-oikea').click(function (e) {
            e.preventDefault();
            if (this.id == 'nuoli-oikea') {
                if (cartIndex < cartLimit) cartIndex++;
            } else {
                if (cartIndex > 0) cartIndex--;
            }

            if (cartIndex < cartLimit)
                $('#nuoli-oikea').show();
            else
                $('#nuoli-oikea').hide();

            if (cartIndex > 0)
                $('#nuoli-vasen').show();
            else
                $('#nuoli-vasen').hide();

            $('#ownlist-slider').animate({left:'-' + cartIndex * cartItemWidth + 'px'}, 400);
        });
    } else {
        $('#nuoli-vasen,#nuoli-oikea').hide();
    }
    
    //$('#listsharelinkemail a').click(function (e) {
    //    e.preventDefault();
    //    $('#emaillist').toggle();
    //});
    //
    //if (!$('#emaillist').hasClass('sent'))
    //    $('#listsharelinkemail a').click();
    //
    //if ($('#emaillist-form').length)
    //    $('#emaillist-form').validate();

    $("#avaa-ostoslista,#listaikoni-avaa").click(showCart);
    $("#sulje-ostoslista,#listaikoni-sulje").click(hideCart);

    //Hyphenator.run();
}

function showCart (e)
{
    if (e && e.preventDefault) e.preventDefault();

    cartOpen = true;
    $("#avaa-ostoslista").hide();
    $("#listaikoni-avaa").hide();

    $("#sulje-ostoslista").show();
    $("#listaikoni-sulje").show();

    $("#ostoslista").slideDown("fast");
    $(this).toggleClass("active");
}

function hideCart (e)
{
    if (e && e.preventDefault) { e.preventDefault(); }

    cartOpen = false;
    $("#sulje-ostoslista").hide();
    $("#listaikoni-sulje").hide();

    $("#avaa-ostoslista").show();
    $("#listaikoni-avaa").show();

    $("#ostoslista").slideUp("fast");
    $(this).toggleClass("active");
}

function removeCartItem (e)
{
    e.preventDefault();
    if (this.id) {
        cartRemovedItem = true;
        var id;

        if (this.id == 'tyhjenna-ostoslista') {
            id = 'kaikki';
            $('.padd').text('Lisää ostoslistalle');
            $('.pthumbcontent-print').slideUp();
        } else {
            id = this.id.split('-').pop();
            $('#tocart-' + id).text('Lisää ostoslistalle');
            $('#prod-print-' + id).slideUp();
        }

        var url = '?view=ostoslista&ostoslistalta=' + id;
        trackView(tidy(url));
        $('#header').load(url, loadCart);
    }
}

/* Initialize default page */ 

function initPrint ()
{
    $('.tulosta').click(printCart);
    if (location.hash == '#tulosta') {
        // Change address so that there's no automatic print on refresh
        location.hash = '';

        //scrollToForm();
        printCart();
    }
  
}

function initArvonta()
{
    // Validate contact form
    $('#lottery-form').validate();
    
    $("#saannot-linkki").click(function (e) {
        e.preventDefault();
        $('#kilpailun-saannot-wrapper').slideDown("fast");
    });
    
    $("#sulje-saannot").click(function (e) {
        e.preventDefault();
        $('#kilpailun-saannot-wrapper').slideUp("fast");
    });
}

function printCart (e)
{
    if (e && e.preventDefault) e.preventDefault();

    var url = '?view=ostoslista&partial=print&tulostettu';
    trackView(tidy(url));

    // Submit contact form
    //$('#printtilomake-form').submit();

    window.print();
}

/* Initialize default page */ 

var productContainer,
    productBuffer,
    loadedProduct;
function initDefault ()
{
    productContainer = $('<div>').css({ 'float': 'left', width: '953px', display: 'none' });
    productBuffer = productContainer.clone();

    $('.pthumbcontent').live('click', loadProduct);

    /* Attach cart refresh to add links */
    $('.padd, .paddIcon').live('click', function (e) {
        e.preventDefault();
        if (this.id) {
            var id = this.id.split('-').pop();
            $('#tocart-' + id + ',#tocart2-' + id).text('Lisätty ostoslistalle');
            //var count = $('#dialogtocart-' + id + ' strong:last');
            //count.text(parseInt(count.text(), 10) + 1); 

            var url = '?view=ostoslista&ostoslistalle=' + id;
            trackView(tidy(url));
            $('#header').load(url, loadCart);
        }

        // Reset timer
        if (cartTimer) {
            clearTimeout(cartTimer);
            cartTimer = setTimeout(hideCart, 1000);
        }

        // Show cart and set timer
        if (!cartOpen) {
            showCart();
            if (!cartTimer)
                cartTimer = setTimeout(hideCart, 1000);
        }
    });
    
    $('.availability-tooltip').cluetip({
        showTitle: false, 
        positionBy: 'mouse',
        topOffset: -15,  
        leftOffset: 15,
        clickThrough: true,
        arrows: true
    });
    
    /* New */

    $('#tuotelista').infinitescroll({
        navSelector: "#tuotelistanselaus",
        nextSelector: "#tuotelistanselaus .sivuseuraava",
        itemSelector: "#tuotelista .pthumb",
        loadingImg: "img/loading.gif",
        loadingText: "<strong>Ladataan tuotteita</strong>",
        donetext: "",
        bufferPx: 244
    }, function (items) {
        $(items).find('.availability-tooltip').cluetip({
            showTitle: false, 
            positionBy: 'mouse',
            topOffset: -15,  
            leftOffset: 15,
            clickThrough: true,
            arrows: true
        });
    });
}
        
/* Load product content */
function loadProduct (e)
{
    e.preventDefault();

    var product = $(this).closest('.pthumb');

    // If active, do nothing
    if (product.hasClass('pthumbactive'))
        return;
    
    // Get products and index for last product on row
    var products = $('#tuotelista .pthumb'),
        index = Math.min(products.length - 1, Math.floor(products.index(product) / 5) * 5 + 4);

    // Mark active
    products.removeClass('pthumbactive');
    product.addClass('pthumbactive');

    // Rotate containers
    var tmp = productContainer;
    productContainer = productBuffer;
    productBuffer = tmp;

    // Fetch id
    var id = loadedProduct = this.id.split('-').pop();

    // Load product
    var url = '?view=tuote&id=' + id;
    trackView(tidy(url));

    productContainer.insertAfter(products[index]);
    productContainer.load(url, productLoaded);
}

function productLoaded ()
{
    productContainer.find('.tuote-sulje').click(hideProduct);
    productContainer.find('.tuotteen-saatavuus').cluetip({
        showTitle: false, 
        positionBy: 'mouse',
        topOffset: -15,  
        leftOffset: 15,
        clickThrough: true,
        arrows: true
    });
	
	productContainer.addClass('currentProduct-' + loadedProduct);
	
    productBuffer.slideUp('fast');
    productContainer.slideDown('fast', initProduct);
}

function initProduct ()
{
	
    $('.currentProduct-' + loadedProduct + ' #comment-form').validate({
        submitHandler: sendHandler('#comment-container', initProduct, '/kommentti/tallennettu')
    });

    $('#email-form').validate({
        submitHandler: sendHandler('#comment-container', initProduct, '/email/tuote')
    });

    $('#lisaa-kommentti,#email').hide();
    //$('#lisaa-kommentti h2,#email h2').click(function (e) {
    //    $('#lisaa-kommentti,#email').hide();
    //    $('#kommentit').show();
    //});
    $('.email-link').click(function (e) {
        e.preventDefault();
        $('#kommentit,#lisaa-kommentti').hide();
        $('#email').show();
    });
    $('.comment-link').click(function (e) {
        e.preventDefault();
        $('#kommentit,#email').hide();
        $('#lisaa-kommentti').show();
    });

    productBuffer.empty();

    if (loadedProduct) {
        $('html,body').scrollable().animate({ scrollTop: $('#prod-' + loadedProduct).offset().top - $('#header').height() - 5 }, 400);
    }
}

function hideProduct (e)
{
    e.preventDefault();

    $('#tuotelista .pthumb').removeClass('pthumbactive');
    productContainer.slideUp('fast');
}

/* Initialize syke page */ 

function initSyke ()
{    
    fetchUpdates($('#fb-updates'), 1, true);
    fetchUpdates($('#fb-updates-syke'), 5);

    $("#sulje-lue-lisaa").hide();
    
    $("#lue-lisaa").click(function(e){
        e.preventDefault();
        $("#sulje-lue-lisaa").show();
        $("#lue-lisaa").hide();
        $("#syke-palkki-laajennettu").slideDown("fast");
        $(this).toggleClass("active");
    });
    
    $("#sulje-lue-lisaa").click(function(e){
        e.preventDefault();
        $("#sulje-lue-lisaa").hide();
        $("#lue-lisaa").show();
        $("#syke-palkki-laajennettu").slideUp("fast");
        $(this).toggleClass("active");
    });
};

/* Parse feeds */

var videoFeed = "http://gdata.youtube.com/feeds/base/users/XXX/uploads?alt=rss&v=2&orderby=published&max-results=50",
    fbFeed = "http://www.facebook.com/feeds/page.php?format=atom10&id=62340449848";

function fetchUpdates (container, amount, summary)
{
    summary = summary || false;

    container.hide();

    var html = '',
        feed = new google.feeds.Feed(fbFeed);
    feed.setNumEntries(amount);
    feed.load(function(result) {
        if (!result.error) {
            for (var i = 0; i < result.feed.entries.length; i++) {
                var entry = result.feed.entries[i];
                var content = entry.content.replace(/href="\/([^"]+)"/g, function (m0, m1) {
                    return 'href="http://www.facebook.com/' + m1 + '" target="_blank"';
                });
            
                // "title", "link", "content", "contentSnippet"
                    
                if (summary) {
                    content = content.replace(/<br>/g," ");
                    html += '<div>' +
                              '<a href="http://www.facebook.com/sokostavaratalot" target="_blank"><img class="syke-fb-ikoni" src="img/facebook.gif"/></a><p class="syke-palkki-pvm">' + formatDate2(entry.publishedDate) + '</p>' +
                              '<p class="syke-palkki-teksti">' + (content.length > 90 ? content.substr(0,90) + '...' : content) + '</p>' +
                              '</div>';
                } else {
                    /* Fix relative links */
                    content = entry.content.replace(/href="\/([^"]+)"/g, function (m0, m1) {
                        return 'href="http://www.facebook.com/' + m1 + '" target="_blank"';
                    });
                    html += '<div class="viesti-wrapper">' +
                              '<a href="http://www.facebook.com/sokostavaratalot" target="_blank"><img class="syke-fb-ikoni" src="img/facebook.gif"/></a><p class="syke-palkki-pvm">' + formatDate2(entry.publishedDate) + '</p>' +
                              '<p class="syke-palkki-teksti">' + content + '</p>' +
                              '</div>';
                }
            }
            container.html(html);
            container.fadeIn(250);
        }
    });
}

function formatDate (string)
{
    var date = new Date(string);

    return date.getDate() + '.' + (date.getMonth() + 1) + '.' + 
        ' klo ' + date.getHours() + ':' + ('0' + date.getMinutes()).substr(0,2);
}
function formatDate2 (string)
{
    var date = new Date(string);

    return date.getDate() + '.' + (date.getMonth() + 1) + '.' + date.getFullYear() + ': ';
}

//function initPrint ()
//{
//    $('#lottery-form').validate();
//}

/*
function showVideo (videoElement)
{
    swfobject.embedSWF( "http://www.youtube.com/v/" + videoElement.id + "?enablejsapi=1&playerapiid=ytplayer", "videoContainer", "490", "368", "8", "/files/lakerol/flash/expressInstall.swf", null, { menu: 'false', wmode: 'transparent', allowScriptAccess: "always" }, { id: "videoContainer" });
}
*/

/* DEPRECATED */

/* Set up dialog and helper functions */ 

var dialogProducts,
    dialogIndex,
    dialogVideos,
    dialogVideoIndex,
    dialogContent;

function initDialog ()
{
    dialogContent = $('<div>').appendTo('body');
    
    /* Initialize modal dialog */
    dialogContent.dialog({
        autoOpen: false,
        modal: true,
        width: 572,
        title: ''
    });
    /* Fix overflow */
    dialogContent.parent().css('overflow', 'visible');

    /* Make the dialog disappear when clicking the overlay */
    $('.ui-widget-overlay,.ui-dialog-content h2:first,.close-dialog').live('click', closeDialog);

    /* Attach dialog to product links */
    $('.prod-link,.prodimg-link,.fav-link,.list-link,.arrow-link').click(function (e) {
        e.preventDefault();

        dialogProducts = $('.' + this.className.split(' ').pop());
		
		dialogIndex = dialogProducts.index(this);

        productDialog();
    });

    $('.prev-link,.next-link').live('click', function (e) {
        e.preventDefault();
        
        if ($(this).hasClass('prev-link'))
            dialogIndex--;
        else
            dialogIndex++;

        productDialog();
    });

    /* Attach dialog to video links */
    $('.prev-video,.next-video').live('click', function (e) {
        e.preventDefault();
        
        if ($(this).hasClass('prev-video'))
            dialogVideoIndex--;
        else
            dialogVideoIndex++;

        videoDialog();
    });

    /* Attach dialog to lottery links */
    $('#arvontalinkkinosto').click(function (e) {
        e.preventDefault();
        lotteryDialog();
    });

    /* Attach dialog to email links */
    $('.email-link').click(function (e) {
        e.preventDefault();
        emailDialog();
    });

    
    /* Attach cart refresh to add links */
    $('.padd,#productlinkslarge .cart-link').live('click', function (e) {
        e.preventDefault();
        if (this.id) {
            var id = this.id.split('-').pop();
            $('#tocart-' + id + ',#dialogtocart-' + id + ' strong:first').text('Lisätty ostoslistalle');
            //var count = $('#dialogtocart-' + id + ' strong:last');
            //count.text(parseInt(count.text(), 10) + 1); 

            var url = '?view=ostoslista&ostoslistalle=' + id;
            trackView(tidy(url));
            $('#ownlist-reload').load(url, loadCart);
        }
    }).cluetip({
        showTitle: false, 
        positionBy: 'fixed',
        topOffset: -15,  
        leftOffset: -15,
        clickThrough: true,
        arrows: true
    });;
}

function openDialog ()
{
    Cufon.replace('.ui-dialog h2', { fontFamily: 'amertype' });
    Cufon.replace('.ui-dialog h4', { fontFamily: 'futuramedium' });
    Cufon.replace('.ui-dialog cite', { fontFamily: 'futuramedium' });
    Cufon.replace('.ui-dialog em', { fontFamily: 'futuracondxbold' });

    var left = $('#updates').offset().left - $('body').scrollLeft();
    dialogContent.dialog('option', 'position', [left, 100]);
    dialogContent.dialog('open');
};

function closeDialog (e)
{
    e.preventDefault();
    dialogContent.dialog('close');
};
        
/* Load product content to dialog */
function productDialog ()
{
    var id = 0, next = 0, prev = 0;

    /* Fetch ids for current, next and previous products */
    id = dialogProducts[dialogIndex].id.split('-').pop();

    if (dialogIndex < dialogProducts.length - 1) 
        next = dialogProducts[dialogIndex+1].id.split('-').pop();

    if (dialogIndex > 0) 
        prev = dialogProducts[dialogIndex-1].id.split('-').pop();

    /* Load dialog */
    var url = '?view=tuote&id=' + id + '&next=' + next + '&prev=' + prev;
    trackView(tidy(url));
    dialogContent.load(url, openContentDialog);
}

/* Load video content to dialog */
function videoDialog ()
{
    var id = 0, next = 0, prev = 0;

    /* Fetch ids for current, next and previous products */
    id = dialogVideos[dialogVideoIndex].id.substr(6);

    if (dialogVideoIndex < dialogVideos.length - 1) 
        next = dialogVideos[dialogVideoIndex+1].id.substr(6);

    if (dialogVideoIndex > 0)
        prev = dialogVideos[dialogVideoIndex-1].id.substr(6);

    /* Load dialog */
    var url = '?view=video&id=' + id + '&next=' + next + '&prev=' + prev;
    trackView(tidy(url));
    dialogContent.load(url, openContentDialog);
}

/* Handle submitting comments and email in product and video dialogs */
function openContentDialog ()
{
    $('#comment-form').validate({
        submitHandler: sendHandler('#comment-container', openContentDialog, '/kommentti/tallennettu')
    });

    $('#email-form').validate({
        submitHandler: sendHandler('#comment-container', openContentDialog, '/email/tuote')
    });

    $('#comment,#email').hide();
    $('#comment h2,#email h2').click(function (e) {
        $('#comment,#email').hide();
        $('#comments').show();
    });
    $('.email-link').click(function (e) {
        e.preventDefault();
        $('#comments,#comment').hide();
        $('#email').show();
    });
    $('.comment-link').click(function (e) {
        e.preventDefault();
        $('#comments,#email').hide();
        $('#comment').show();
    });

    $('#add-recipient').click(function (e) {
        e.preventDefault();
        var count = $('input[name="recipient[]"]').length;
        if (count >= 2) $(this).hide();

        var html = '<label for="comment-recipient-{0}">Vastaanottaja {1} sähköposti</label>' +
                   '<br />' +
                   '<input style="width:300px" class="email" id="comment-recipient-{0}" ' +
                          'name="recipient[]" value="" maxlength="255" />' +
                   '<br />';
            
        $(this).before(html.insert(count, count + 1));
    });

    openDialog();
}

/* Load general email form to dialog */
function emailDialog ()
{
    var url = '?view=email';
    trackView(tidy(url));
    dialogContent.load(url, openEmailDialog);
}

/* Handle submitting comments and email in product and video dialogs */
function openEmailDialog ()
{
    $('#email-form').validate({
        submitHandler: sendHandler('#comment-container', openEmailDialog, '/email/sivu')
    });

    $('#add-recipient').click(function (e) {
        e.preventDefault();
        var count = $('input[name="recipient[]"]').length;
        if (count >= 2) $(this).hide();

        var html = '<label for="comment-recipient-{0}">Vastaanottaja {1} sähköposti</label>' +
                   '<br />' +
                   '<input style="width:300px" class="email" id="comment-recipient-{0}" ' +
                          'name="recipient[]" value="" maxlength="255" />' +
                   '<br />';
            
        $(this).before(html.insert(count, count + 1));
    });

    openDialog();
}

/* Load lottery form to dialog */
function lotteryDialog ()
{
    var url = '?view=arvonta';
    trackView(tidy(url));
    dialogContent.load(url, openLotteryDialog);
}

/* Handle submitting lottery form */
function openLotteryDialog ()
{
    $('#lottery-form').validate({
        submitHandler: sendHandler(dialogContent, openLotteryDialog, '/arvonta/osallistuminen')
    });

    openDialog();
}
        

/* Initialize favorites list */

function initFavorites ()
{
var favIndex = 0,
    favPerPage = 5,
    favLength = $('#toplistsmall li').length;

    if (favLength > favPerPage) {
        $('#toplistsmall')
            .css({position:'absolute',left:'0px',top:'0px',width:'190px'});
            //.wrap('<div id="toplist-container" style="position:relative;overflow:hidden;width:190px;" />');

        $('#toplist-container').height($('#toplistsmall li').eq(favPerPage).position().top + 'px');

        $('#toplistbrowse a').click(function (e) {
            e.preventDefault();
            if ($(this).parent().hasClass('seuraavat')) {
                if (favIndex < Math.ceil(favLength / favPerPage) - 1) favIndex++;
            } else {
                if (favIndex > 0) favIndex--;
            }

            var offset = $('#toplistsmall li').eq(favIndex * favPerPage).position().top,
                offset2;
            if (favLength <= (favIndex + 1) * favPerPage) {
                //item = $('#toplistsmall li').last();
                //offset2 = item.position().top + item.height();
                offset2 = $('#toplistsmall').height();
            } else {
                var item = $('#toplistsmall li').eq((favIndex + 1) * favPerPage);
                offset2 = item.position().top;
            }

            $('#toplist-container').animate({height: (offset2 - offset) + 'px'}, 500);
            $('#toplistsmall').animate({top:'-' + offset + 'px'}, 500);
        });
    } else {
        $('#toplistbrowse').hide();
    }
}

/* Init Cufon */

function initCufon ()
{
    Cufon.replace('h2', { fontFamily: 'amertype' });
    Cufon.replace('h4', { fontFamily: 'futuramedium' });
    Cufon.replace('cite', { fontFamily: 'futuramedium' });
    Cufon.replace('em', { fontFamily: 'futuracondxbold' });
}

//var sykeClosed = false;
//function initDefault ()
//{
//    $('#updatesheading').addClass('sulje');
//    $('#updatesheading').click(function (e) {
//        sykeClosed = !sykeClosed;
//        setCookie('syke', sykeClosed ? 1 : 0);
//        if (sykeClosed) {
//            $(this).addClass('sulje');
//            $(this).attr("src", "img/shoppailuopas2.gif");
//            $('#syke').show();
//            $('#shoppailuopas').hide();
//            
//        } else {
//            $(this).removeClass('sulje');
//            $(this).attr("src", "img/shoppailuopas.gif");
//            $('#syke').hide();
//            $('#shoppailuopas').show();
//        }
//    });
//
//    /* Hide when user has closed syke or after store has been selected */
//    if ($('.storelistsection input[type=radio]:checked').length || getCookie('syke') == 1)
//        $('#updatesheading').click();
//
//    fetchVideos($('#yt-videos'), 2);
//}

function fetchVideos (container, amount)
{
    var html = '',
        feed = new google.feeds.Feed(videoFeed);
    feed.setNumEntries(amount);
    feed.load(function(result) {
        if (!result.error) {
            for (var i = 0; i < result.feed.entries.length; i++) {
                var entry = result.feed.entries[i],
                    code = entry.link.match(/[?&]v=([^&]+)&?/)[1];

                html += '<div>' +
                          '<h4>' + formatDate(entry.publishedDate) + '</h4>' +
                          '<a id="video-' + code + '" href="./video/id:' + code + '" class="video-link">' +
                            '<img src="http://i.ytimg.com/vi/' + code + '/default.jpg" alt="" />' +
                          '</a>' +
                        '</div>';
            }

            container.html(html);
            container.find('a.video-link').click(function (e) {
                e.preventDefault();

                dialogVideos = $('.' + this.className);
                dialogVideoIndex = dialogVideos.index(this);

                videoDialog();
            });
        }
    });
}

var tinkainIndex = 0,
    tinkainPerPage = 1,
    tinkainItemWidth = 620,
    tinkainLength,
    tinkainLimit;

function initTinkain ()
{
    // Attach events to like buttons
    FB.Event.subscribe('edge.create', likeTinkain);
    FB.Event.subscribe('edge.remove', unlikeTinkain);

    // Show and hide tinkain elements
    $('.tinkainohjeet').click(function (e) {
        e.preventDefault();
        $('#laske-hintaa').hide();
        $('#tinkain-ohje-wrapper').show();
        $('#tinkain-edellinen, #tinkain-seuraava').hide();
    });    
    
    $('#sulje-tinkain-ohje').click(function (e) {
        e.preventDefault();
        $('#laske-hintaa').show();
        $('#tinkain-ohje-wrapper').hide();
        $('#tinkain-edellinen, #tinkain-seuraava').show();
    });
    
    $('.tinkain-tuotteen-tiedot-link').click(function (e) {
        e.preventDefault();
        $('.tinkain-tiedot').hide();
        $('.tinkain-tuotteen-tiedot-link').hide();
        $('.tinkain-tuotteen-tiedot').show();
        $('.tinkain-sulje-tuotteen-tiedot-link').show();
    });
    
    $('.tinkain-sulje-tuotteen-tiedot-link').click(function (e) {
        e.preventDefault();
        $('.tinkain-tiedot').show();
        $('.tinkain-tuotteen-tiedot-link').show();
        $('.tinkain-tuotteen-tiedot').hide();
        $('.tinkain-sulje-tuotteen-tiedot-link').hide();
    });

    // Show and hide tuoterivi
    $('#tuoterivi').addClass('closed');
    $(".btn-listalinkki").live('click', function (e) {
        e.preventDefault();
        if ($('#tuoterivi').hasClass('closed')) {
            $(".avaa-tinkaintuotteet").hide();
            $(".sulje-tinkaintuotteet").show();
            $("#tuoterivi").slideDown("fast");
            $('#tuoterivi').removeClass('closed');
        } else {
            $('#tuoterivi').slideUp("fast");    
            $('#tuoterivi').addClass('closed');
            $(".avaa-tinkaintuotteet").show();
            $(".sulje-tinkaintuotteet").hide();
        }
    });

    // Tinkain slideshow

    tinkainLength = $('.tinkain-tuote-wrapper').length;
    tinkainLimit = Math.max(0, tinkainLength - tinkainPerPage);
    var index = $('.tinkain-tuote-wrapper').index($('.tinkain-tuote-wrapper.active'));
    if (index > 0)
        tinkainIndex = index;

    /* Restore previous styles */
    $('.tinkain-slider').css({
        width: tinkainLength * tinkainItemWidth,
        left: '-' + tinkainIndex * tinkainItemWidth + 'px'
    });
    
    if (tinkainIndex == 0)
        $('#tinkain-edellinen').hide();

    if (tinkainLength > tinkainPerPage) {

        /* Attach browsing events  */
        $('#tinkain-edellinen,#tinkain-seuraava').click(function (e) {
            e.preventDefault();
            if (this.id == 'tinkain-seuraava') {
                if (tinkainIndex < tinkainLimit) tinkainIndex++;
            } else {
                if (tinkainIndex > 0) tinkainIndex--;
            }

            if (tinkainIndex < tinkainLimit)
                $('#tinkain-seuraava').show();
            else
                $('#tinkain-seuraava').hide();

            if (tinkainIndex > 0)
                $('#tinkain-edellinen').show();
            else
                $('#tinkain-edellinen').hide();

            
            $('.tinkain-slider').animate({left:'-' + tinkainIndex * tinkainItemWidth + 'px'}, 400);
        });
    } else {
        $('#tinkain-edellinen,#tinkain-seuraava').hide();
    }

    $('#tuoterivi .pthumbcontent-ostoslista').click(function (e) {
        e.preventDefault();

        var tinkainIndex = this.id.split('-').pop();
        $('.tinkain-slider').animate({left:'-' + tinkainIndex * tinkainItemWidth + 'px'}, 400);
    });
}

function likeTinkain (href, widget)
{
    var id = href.split(':')[2];

    if (id) {
        trackView(tidy('?like=' + id));
        $.post('?view=tinkain', { like: id }, likeHandler, 'json');
    }
	
	$('.tinkaa-like .fbbutton').html('<span>Kiitos &ndash; Tinkauksesi on nyt huomioitu.</span>');
}

function unlikeTinkain (href, widget)
{
    var id = href.split(':')[2];

    if (id) {
        trackView(tidy('?unlike=' + id));
        $.post('?view=tinkain', { unlike: id }, likeHandler, 'json');
    }
}

function likeHandler (data)
{
    $('.active .tinkain-hinta').text(data.currentprice);
	
	Cufon.replace('.active .tinkain-hinta', { fontFamily: 'Orator Std' });

    //Cufon.replace('.active .tinkain-hinta');
}

function saveLike()
{
    var vID = $('#youtube_container').attr('class');
    var parsedID = vID.split("_");
    //alert(parsedID[1]);
    $.ajax({
        url: "../inc/like.php",
        type: "POST",
        data: {id : parsedID[1]},
        success: function(msg) {
            //alert('success' + msg);
        },
        error:  function(msg) {
            //alert('error' + msg);
        }
    });
}


//function initSearch ()
//{
//    $("#storeform .storelistsection").accordion({ header: 'h3' });
//
//    if ($('.storelistsection input[type=radio]:checked').length) {
//        $('#storeform').hide();
//        $('#searchform').show();
//    } else {
//        $('#searchform').hide();
//        $('#storeform').show();
//    }
//
//    $('#storeform input[type=radio]').click(function (e) {
//        $('.storelistsection input[type=radio]').not(this).removeAttr('checked');
//        $('#search-form').submit();
//        /*
//        $('#storeform').hide();
//        $('#searchform').show();
//        */
//    });
//
//    $('.storelisttrigger a').click(function (e) {
//        e.preventDefault();
//        $('#searchform').hide();
//        $('#storeform').show();
//    });
//
//    $('.shortsearchinput').focus(function (e) {
//        if (this.value == this.title)
//            this.value = '';
//    });
//
//    $('.shortsearchinput').blur(function (e) {
//        if (this.value == '')
//            this.value = this.title;
//    }).blur();
//
//    $('#search-form,#free-form').submit(function (e) {
//        if ($('.shortsearchinput')[0].value == $('.shortsearchinput')[0].title)
//            $('.shortsearchinput')[0].value = '';
//    });
//}


