$(document).ready(function () {
    initDialog();
    initSearch();
    initFavorites();
    initCart();

    $.validator.messages.digits = '';
    $.validator.messages.email = 'tarkista oikeinkirjoitus';
    $.validator.messages.required = 'pakollinen';

    var bodyId = $('body').attr('id'),
        action = {
            'page-default': initDefault,
            'page-syke': initSyke,
            'page-tuote': initCufon
        };

    if (action[bodyId]) action[bodyId]();

});

/* 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)
{
    snoobi.trackPageView(code);
    pageTracker._trackPageview(code);
}

/* Init Cufon */

function initCufon ()
{
    Cufon.replace('h2', { fontFamily: 'amertype' });
    Cufon.replace('h4', { fontFamily: 'futuramedium' });
    Cufon.replace('cite', { fontFamily: 'futuramedium' });
    Cufon.replace('em', { fontFamily: 'futuracondxbold' });
}

/* 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();
    });

	/*$(".availability-tooltip").cluetip({
		showTitle: false, 
		positionBy: 'fixed',
		topOffset: -5,  
		leftOffset: -15,
		arrows: true
	  });*/
	
    /* 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, initCart);
        }
    }).cluetip({
		showTitle: false, 
		positionBy: 'fixed',
		topOffset: -5,  
		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();
}

/* Handle sending forms */
function sendHandler (target, callback, code)
{
    return function (form) {
        trackView(code);
        $(form).ajaxSubmit({target: target, success: callback});
    };
}

/* Initialize search */ 

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 = '';
    });
}

/* 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();
    }
}

/* Initialize shopping list */

function initCart ()
{
    var cartIndex = 0,
        cartPerPage = 10,
        cartLength = $('#ownlistsmall li').length;

    if (cartLength > cartPerPage) {
        $('#ownlistsmall')
            .css({position:'absolute',left:'0px',top:'0px',width:'190px'})
            .wrap('<div id="ownlist-container" style="position:relative;overflow:hidden;width:190px;" />');

        $('#ownlist-container').height($('#ownlistsmall li').eq(cartPerPage).position().top + 'px');

        $('#ownlistbrowse a').click(function (e) {
            e.preventDefault();
            if ($(this).parent().hasClass('seuraavat')) {
                if (cartIndex < Math.ceil(cartLength / cartPerPage) - 1) cartIndex++;
            } else {
                if (cartIndex > 0) cartIndex--;
            }

            var offset = $('#ownlistsmall li').eq(cartIndex * cartPerPage).position().top,
                offset2;
            if (cartLength <= (cartIndex + 1) * cartPerPage) {
                //item = $('#ownlistsmall li').last();
                //offset2 = item.position().top + item.height();
                offset2 = $('#ownlistsmall').height();
            } else {
                var item = $('#ownlistsmall li').eq((cartIndex + 1) * cartPerPage);
                offset2 = item.position().top;
            }

            $('#ownlist-container').animate({height: (offset2 - offset) + 'px'}, 500);
            $('#ownlistsmall').animate({top:'-' + offset + 'px'}, 500);
        });
    } else {
        $('#ownlistbrowse').hide();
    }
    
    $('#listsharelinkemail a').click(function (e) {
        e.preventDefault();
        $('#emaillist').toggle();
    });

    if (!$('#emaillist').hasClass('sent'))
        $('#listsharelinkemail a').click();

    if ($('#emaillist-form').length)
        $('#emaillist-form').validate();
}



/* Initialize default page */ 

var sykeClosed = false;
function initDefault ()
{
    $('#updatesheading').addClass('sulje');
    $('#updatesheading').click(function (e) {
        sykeClosed = !sykeClosed;
        setCookie('syke', sykeClosed ? 1 : 0);
        if (sykeClosed) {
            $(this).removeClass('sulje');
			$(this).attr("src", "img/sothisseason/shoppailuopas2.gif");
            $('#sykenostot,#updatescontent').hide();
        } else {
            $(this).addClass('sulje');
			$(this).attr("src", "img/sothisseason/shoppailuopas.gif");
            $('#sykenostot,#updatescontent').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();

    fetchUpdates($('#fb-updates'), 2, true);
    //fetchVideos($('#yt-videos'), 2);
}
        
/* Initialize syke page */ 

function initSyke ()
{
    fetchUpdates($('#fb-updates'), 25);
    //fetchVideos($('#yt-videos'), 6);
};

/* 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 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();
            });
        }
    });
}

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],
                    content;

                if (summary) {
                    content = '<a href="./syke">' + entry.contentSnippet + '</a>';
                } else {
                    /* Fix relative links */
                    content = entry.content.replace(/href="\/([^"]+)"/g, function (m0, m1) {
                        return 'href="http://www.facebook.com/' + m1 + '" target="_blank"';
                    });
                }

                // "title", "link", "content"
                html += '<div>' +
                          '<h4>' + formatDate(entry.publishedDate) + '</h4>' +
                          '<p>' + 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 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" });
}
*/
