﻿var rsSearchTimer;
var rsFeedPage = 1;
var rsQueryString = {};
jQuery(function ($) {

    window.location.href.replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function ($0, $1, $2, $3) { rsQueryString[$1] = $3; }
    );

    $('#hide-splash').click(function () {
        $('#head0').hide();
        $.cookie('rocksho-hide-splash', '1');
        return false;
    });
    rocksho_labelify();
    rocksho_rollovers();
    rocksho_enable_ajax_links();
    rocksho_enable_calendar_hover();
    rocksho_feed_videoplayer();

    $('#title-search')
        .keypress(function (e) {
            if ($(this).val().length > 0 && e.which == 13) {
                window.location.href = '/?search=' + encodeURI($(this).val());
                e.stopPropagation();
                e.preventDefault();
                return false;
            }
            if ($(this).val().length > 1) {
                if (rsSearchTimer) clearTimeout(rsSearchTimer);
                var that = this;
                rsSearchTimer = setTimeout(function () {
                    $.get('/?action=search&async=1', { searchfor: $(that).val() }, function (response) {
                        $('#title-search-results').html(response);
                    });
                    rsSearchTimer = null;
                },
                400);
            }
            else if ($(this).val() == '') {
                if (rsSearchTimer) clearTimeout(rsSearchTimer);
                rsSearchTimer = null;
                $('#title-search-results').html('');
            }
        })
        .focus(function () {
            $('#title-search-results').show();
        })
        .blur(function () {
            setTimeout(function () { $('#title-search-results').hide(); }, 200);
        });

    $('#loadMore').click(function () {
        $('#loadMore').hide();
        $('#loadMore-loading').show();
        rsFeedPage++;
        $.get('', { page: rsFeedPage }, function (response) {
            $('#loadMore').show();
            $('#loadMore-loading').hide();
            var domResponse = $(response);
            $('#UserFeed').append(domResponse.find('#UserFeed').html());
            if (domResponse.find('#loadMore').length == 0) $('#loadMore').hide();
            if (rsFeedPage >= 5) $('#loadMore').hide();
            rocksho_feed_videoplayer();
        });
        return false;
    });

    $('#location-change-submit').click(function () {
        $('#location-change-wait').show();
        $('#location-change-cancel').hide();
        $('#location-change-submit').hide();

        $.get('', { action: 'change-location', async: 1, postalCode: $('#changePostalCode').val() }, function (response) {
            $('#location-change-wait').hide();
            $('#location-change-cancel').show();
            $('#location-change-submit').show();

            var domResponse = $(response);
            var locationError = domResponse.find('#locationError');
            if (locationError.css('display') != 'none') {
                $('#locationError').html(locationError.html()).show();
                setTimeout(function () { $('#locationError').hide(); }, 10000);
            }
            else {
                $('#location-name').html(domResponse.find('#location-name').html());
                $('#UserFeed').html(domResponse.find('#UserFeed').html());
                $('#location-display').show();
                $('#location-change').hide();
            }
            rsFeedPage = 1;
            rocksho_feed_videoplayer();
        });

        return false;
    });
    $('#changePostalCode').keypress(function (e) {
        if (e.which == 13) {
            $('#location-change-submit').click();
            return false;
        }
    }).focus(function () {
        $('#location-shofinder-hint').fadeOut(100);
    });
    $('#location-change-cancel').click(function () {
        $('#location-display').show();
        $('#location-shofinder-hint:visible').fadeOut(100);
        $('#location-change').hide();
        return false;
    });
    $('#location-change-link').click(function () {
        $('#location-display').hide();
        $('#location-change').show();
        $('#location-shofinder-hint').fadeIn(100);
        return false;
    });

    if ($.browser.msie) {
        $('.feed-image img').click(function () {
            window.location.href = $(this).parents('.feed-image').attr('href');
        });
    }

    rocksho_preload([
        '/images/v2/account_menu_top.png',
        '/images/v2/account_menu_bg.png',
        '/images/v2/account_menu_bottom.png',
        '/images/v2/btn1_sm_h.gif',
        '/images/v2/btn1_med_h.gif',
        '/images/v2/btn1_lg_h.gif',
        '/images/v2/btn2_sm_h.gif',
        '/images/v2/btn2_med_h.gif',
        '/images/v2/btn2_lg_h.gif'
    ]);

    if ($.datepicker) {
        $('.datepicker').datepicker({
            showOtherMonths: true
        });
    }

    $('ul.selector li').click(function () {
        jQuery(this).parent('ul').find('li').removeClass('current');
        jQuery(this).addClass('current');
    });

    /* perhaps a future idea, for now it conflicts with all the javascript that needs to run on load
    $('#shofinder-change-search').click(function () {
        jQuery('#shofinder_ajax_form').show();
        jQuery('#shofinder_html').load('/shofinder/default.aspx #shofinder', rsQueryString, function () {
            jQuery('#shofinder_loading').fadeOut();
            jQuery('#shofinder_html').slideDown();
            jQuery('#divShofinderCrumbs').slideUp();
        });
        jQuery('#shofinder-change-search').unbind('click');
        return false;
    });
    */
});

function submitTitleSearch(noredirect) {
    window.location.href = '/?search=' + encodeURI($('#title-search').val() + (noredirect ? '&noredirect=true' : ''));
}
function rocksho_feed_videoplayer() {
    $('.video-item-description a.play').unbind('click').click(function () {
        var playerContainer = $(this).parents('.video-item-description').hide().siblings('.video-item-player').show();
        var video_id = playerContainer.find('input[type=hidden]').val();
        var params = { allowScriptAccess: "always", wmode: 'transparent' };
        var atts = { id: "myytplayer-" + video_id };
        swfobject.embedSWF("http://www.youtube.com/e/" + video_id + "?autoplay=1&enablejsapi=0&playerapiid=ytplayer-" + video_id,
            "ytplayer-wrap-" + video_id, "480", "360", "8", null, null, params, atts);
        return false;
    });
}
function rocksho_rollovers() {
    var load_rollover = function () {
        if ($(this).is('img')) {
            var src = $(this).attr('src');
            var ftype = src.substring(src.lastIndexOf('.'));
            var hsrc = src.replace(ftype, '_h' + ftype);
            var preload = new Image();

            preload.src = hsrc;
            $(this).data('src', src).data('hsrc', hsrc);
        }
        else
            $(this).find('img.h').each(load_rollover);
    };
    $('.imgover')
        .each(load_rollover)
        .hover(
            function () {
                $(this).add($(this).find('img.h')).filter('img').each(function () {
                    $(this).attr('src', $(this).data('hsrc'));
                });
            },
            function () {
                $(this).add($(this).find('img.h')).filter('img').each(function () {
                    $(this).attr('src', $(this).data('src'));
                });
            }
        );
}
function rocksho_labelify(within) {
    if (typeof (within) == 'undefined') within = '';
    else within += ' ';
    $(within + '.labeltext')
        .each(function () {
            $(this).data('default', this.defaultValue);
            this.value = this.defaultValue;
            this.defaultValue = '';
        })
        .labelify({ labelledClass: "label" })
        .attr('title', '')
        .focus(function () {
            if (this.value === $(this).data('default')) this.select();
        });
    $(within + '.labeltext-ext')
        .each(function () {
            $(this).data('default', this.defaultValue);
            this.value = this.defaultValue;
            this.defaultValue = '';
            var labeltag = $('label[for=' + this.id + ']').hide();
            labeltag.html(labeltag.html().replace(":", ""));
        })
        .labelify({ labelledClass: "label", text: "label" })
        .focus(function () {
            if (this.value === $(this).data('default')) this.select();
        });
}
function rocksho_enable_ajax_links() {
    jQuery('a.ajax_enabled').unbind('click').click(function () {
        var link = this;
        jQuery('body').addClass('busy');
        jQuery.get(this.href, { async: 1 }, function (data, textStatus) {
            jQuery('body').removeClass('busy');
            if (data.success == 1 && typeof (data.replaceWith) == 'string') jQuery(link).replaceWith(data.replaceWith);
            if (typeof (data.redirectUrl) == 'string') window.location.href = data.redirectUrl;
            if (typeof (data.updateList) == 'object' && (data.updateList instanceof Array)) {
                for (var i = 0; i < data.updateList.length; i++) {
                    jQuery(data.updateList[i].selector).html(data.updateList[i].innerHTML);
                }
            }
            if (typeof (data.executeScript) == 'string') eval(data.executeScript);
        }, 'json');
        return false;
    });
}
function rocksho_enable_calendar_hover() {
    jQuery('.rocksho-calendar-on').hover(
                function () { jQuery(this).parent().parent().addClass('rocksho-hover'); },
                function () { }
                );
    jQuery('.rocksho-calendar-remove').hover(
                function () { },
                function () { jQuery(this).parent().removeClass('rocksho-hover'); }
                );
}
function onYouTubePlayerReady(playerid) {
    $(playerid).get(0).playVideo();
}
function rocksho_preload(images) {
    if ($.isArray(images)) {
        $.each(images, function (index, src) {
            var preload = new Image();
            preload.src = src;
        });
    }
}
