/*----------------------------------------------------------
| |  (_)         | |                             (_) |   
| | ___ _ __   __| | ___ _ __ _ __ ___  _   _ ___ _| | __
| |/ / | '_ \ / _` |/ _ \ '__| '_ ` _ \| | | / __| | |/ /
|   <| | | | | (_| |  __/ |  | | | | | | |_| \__ \ |   < 
|_|\_\_|_| |_|\__,_|\___|_|  |_| |_| |_|\__,_|___/_|_|\_\ .js
------------------------------------------------------------*/

// Get global locale prefix
global_locale_prefix = '/' + document.location.pathname.split('/')[1];

//------------------------------------------------
// Utility
//------------------------------------------------

function obj_to_querystring(obj) {
    var querystring = '';
    
    for(key in obj) {
        querystring += key + '=' + obj[key] + '&';
    }

    return querystring;
}

function querystring_to_obj(querystring) {
    var obj = {};
    
    var args = querystring.split('&');

    for(var i=0; i<args.length; i++) {
        if(args[i] != "") {
            var pair = args[i].split('=');
            var key = decodeURIComponent(pair[0]);
            var value = decodeURIComponent(pair[1]);

            obj[key] = value;
        }
    }

    return obj;
}

jQuery.preloadImages = function() {
    for(var i = 0; i<arguments.length; i++) {
        jQuery("<img>").attr("src", arguments[i]);
    }
}

//------------------------------------------------
// Initialization
//------------------------------------------------

$(function() {
    //------------------------------------------------
    // Browse-by-link hover states
    //------------------------------------------------    
    $.preloadImages(
        MEDIA_URL + "img/browse-by-age_active.png",
        MEDIA_URL + "img/browse-by-style_active.png",
        MEDIA_URL + "img/browse-by-albums_active.png",
        MEDIA_URL + "img/browse-by-theme_active.png",
        MEDIA_URL + "img/browse-by-tracks_active.png"        
    );

    $('#browse-links a').hover(function() {
        $(this).find('img.inactive').hide();
        $(this).find('img.active').show();
    }, function() {
        $(this).find('img.active').hide();
        $(this).find('img.inactive').show();
    });


    //------------------------------------------------
    // Set up modal window(s)
    //------------------------------------------------    
    $('#modal').jqm({modal: true});
    $('#ecard-modal').jqm({modal: true});    
    

    //------------------------------------------------
    // Set up login ajax links
    //------------------------------------------------
    $('#login-link').click(function() {
        $.get(global_locale_prefix + '/ajax/login/', function(response_data) {
            $('#modal').html(response_data);
            $('#modal').jqmShow();
            setup_classcode_tip();
        })
        
        return false;
    });

    //------------------------------------------------
    // Basic qtip options
    //------------------------------------------------
    var qtip_options = {
        content: {
            text: false
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'bottomMiddle'
            }
        },
        show: {
            delay: 10
        },
        style: 'cream'
    };
    $('.qtip').qtip(qtip_options);

    setup_classcode_tip();
    
    //------------------------------------------------
    // Set up 'download' links
    //------------------------------------------------
    
    $('.download-song-link').qtip(qtip_options);
    $('.activity-link').qtip(qtip_options);
    
    
    $('.download-song-link').click(function() {
        var parts = $(this).attr('id').split('-');

        show_confirm_screen(parts[1],parts[2]);
    });


    $('.activity-download-link').click(function() {
        var parts = $(this).attr('id').split('-');
        var href = $(this).attr('href');
        $.post(global_locale_prefix + '/ajax/record_activity_download/',
               {"recording_id": parts[1]},
               function(data) {
                   window.location.href = href;
               });
        
        return false;
    });

    $('.lyrics-download-link').click(function() {
        var parts = $(this).attr('id').split('-');
        var href = $(this).attr('href');
        $.post(global_locale_prefix + '/ajax/record_lyrics_download/',
               {"album_id": parts[1]},
               function(data) {
                   window.location.href = href;
               });
        return false;
    });

    //------------------------------------------------    
    // Set up homepage tabs
    //------------------------------------------------    
    $('.homepage-tab-link').click(function() {
        $('.homepage-tab-link').removeClass('active');
        var tab_name = $(this).attr('id').split('-')[0];
        $('.homepage-tab').hide();
        $('#' + tab_name + '-tab').show();

        $('#homepage-tab-controls').css('background-image', 'url(' + MEDIA_URL + 'img/hp-tabs/' + tab_name + '.png)');

        $(this).addClass('active');
    });

    // check for a tab in the url
    if($.address.value() != "/") {
        var go_to_tab_link = $.address.value().replace('-tab','-link').replace('/','')
        $('#' + go_to_tab_link).click();
    } else {
        if(!is_first_login) {
            $('#kinderpicks-link').click();
        }
    }

    
    //------------------------------------------------
    // Set up input defaults
    //------------------------------------------------    
    $(':input').each(function() {
        // if there's no 'label' attribute we have nothing to do here
        if(typeof($(this).attr('label')) == 'undefined') {
            return;
        }
        
        $(this).blur(function() {
            // revert to the label if no value is entered
            if($(this).val() == '') {
                $(this).val($(this).attr('label'));
            }
        });

        $(this).focus(function() {
            // clear the box if it's just the label
            if($(this).val() == $(this).attr('label')) {
                $(this).val('');
            }
        });

        // initialize
        $(this).blur();
        
    });


    //------------------------------------------------    
    // Set up search filter dialogs
    //------------------------------------------------    
    $('.filterbox').click(function() {

        // first serialize the key/value pairs to be sent into
        // an object.
        var filter_data = {};

        // check for an existing querystring to update, before
        // adding any new data
        if(typeof(filter_querystring) != 'undefined' && filter_querystring != '') {
            filter_data = querystring_to_obj(filter_querystring);
        }

        if(typeof(alpha) != 'undefined') {
            filter_data.alpha = alpha;
        }

        if(typeof(style_page) != 'undefined') {
            filter_data.style_page = style_page;
        }
        
        $('.filterbox').each(function() {
            var val = '0';

            if($(this).attr('checked') == true) {
                val = '1';
            } else {
                val = '0';
            }

            filter_data[$(this).attr('id')] = val;
        });

        // then translate that object to a querystring and redirect
        var new_url = window.location.href.replace(window.location.search,'') + '?' + obj_to_querystring(filter_data);
        
        window.location.href = new_url;
    });

    $('.autosubmit-filter-select').change(function() {
        var filter_data = {};
        
        if(typeof(filter_querystring) != 'undefined') {
            filter_data = querystring_to_obj(filter_querystring);
        }

        filter_data[$(this).attr('name')] = $(this).val();

        var new_url = window.location.href.replace(window.location.search,'') + '?' + obj_to_querystring(filter_data);
        
        window.location.href = new_url;
    });

});

//------------------------------------------------
// Confirm download
//------------------------------------------------    
function show_confirm_screen(content_type, object_id) {

    var object_data = {
        content_type: content_type,
        object_id: object_id
    }

    $.get(global_locale_prefix + "/ajax/download_info/", object_data,
          function(response_data, textStatus) {
              $('#modal').html(response_data.body);
              $('#modal').jqmShow();
          }, 'json');
}

function confirm_download(content_type, object_id) {
    // spend the credits and do the download

    var object_data = {
        content_type: content_type,
        object_id: object_id
    }

    $.post(global_locale_prefix + "/ajax/purchase/", object_data, function(data, textStatus) {
	    kill_modal();
        
        $('#credit-count').html(data.user_credits);
	    $('#download-' + content_type + '-' + object_id).qtip('api').updateContent(gettext('Free Download'));

        $('#modal').html(data.body);
        $('#modal').jqmShow();
        
    }, "json");
}


//------------------------------------------------
// Kill modal window
//------------------------------------------------    
function kill_modal() {
    $('#modal').jqmHide()
    $('#modal-content').empty();

    // rerouting the ecard iframe to stop playback?
    var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );    
    if($.browser.msie || is_chrome) {
        $('#card-frame').attr('src','/');
    }
    $('#ecard-modal').jqmHide()
    $('#ecard-modal-content').empty();
}


//------------------------------------------------    
// Set up 'add credits' page
//------------------------------------------------
function set_up_add_credits_page() {
    $('#id_currency').closest('tr').before(
        '<tr><th>' + gettext('Price per credit:') + '</th><td><span id="per-credit-price"></span></td></tr>');

    $('#id_currency').closest('tr').after(
        '<tr><th>' + gettext('Total:') + '</th><td><span id="total-price"></span></td></tr>');

    $('#id_credits_quantity').bind('keyup', function(e) {
        update_totals();
    });
    
    $('#id_credits_quantity').change(function() {
        update_totals();
    });

    $('#id_currency').change(function() {
        var data = {};
        data['currency'] = $(this).val();
        $.get(global_locale_prefix + '/ajax/price_chart/', data, function(response_data) {
            $('#price-chart-container').html(response_data);
            update_totals();
        });
    });
    
    update_totals();
}

function format_price(float_val) {
    return Number(float_val).toFixed(2);
}

function update_totals() {
    var input_data = $('#id_credits_quantity').val();

    var new_quantity = parseInt(input_data);
    var new_price = '';

    if(isNaN(new_quantity)) {
        new_price = '';
        $('#per-credit-price').html('');
        $('#total-price').html('');
        return;
    } else {
        // find this quantity
        for(var i=0; i< price_chart.levels.length; i++) {
            var level = price_chart.levels[i];

            if(new_quantity >= level.min_quantity &&
               (new_quantity <= level.max_quantity || level.endless)) {
                new_price = parseFloat(level.price);
            }
        }
    }
    
    new_price = new_price.toString();
    $('#per-credit-price').html(price_chart.symbol + format_price(new_price));
    $('#total-price').html(price_chart.symbol + format_price(new_price * new_quantity));
}

function show_spotlight(spotlight_id) {

    var active_id = $('.spotlight-active').attr('id').split('-')[1];
    var num_spotlights = $('.spotlight').length;

    if(spotlight_id == 'next') {
        spotlight_id = parseInt(active_id) + 1;
        if(spotlight_id > num_spotlights) {
            spotlight_id = 1;
        }
    } else if (spotlight_id == 'previous') {
        spotlight_id = parseInt(active_id) - 1;
        if(spotlight_id < 1) {
            spotlight_id = num_spotlights;
        }
    }

    $('.spotlight').removeClass('spotlight-active');
    $('.spotlight').addClass('spotlight-inactive');
    
    $('#spotlight-' + spotlight_id).addClass('spotlight-active');

    $('.spotlight-link').removeClass('active');
    $('#spotlight-link-' + spotlight_id).addClass('active');

}

//------------------------------------------------
// E-Cards
//------------------------------------------------

function ecards_page(page) {
    $.get(global_locale_prefix + '/ajax/ecards/', {'page': page}, function(response_data) {
        $('#ecards-tab-content').html(response_data);
    });
}

function send_ecard(ecard_id) {
    $.get(global_locale_prefix + '/ajax/send_ecard/', {'ecard_id': ecard_id}, function(response_data) {
        $('#ecards-tab-content').html(response_data);
    });
}

function small_preview_ecard(ecard_id) {
    // show the ecard in the 'small preview' area of the ecards tab

    $.get(global_locale_prefix + '/ajax/small_preview_ecard/', {'ecard_id': ecard_id}, function(response_data) {
        $('#small-ecard-preview').html(response_data);
    });
}

function preview_ecard(ecard_id) {
    // check for form elements to preview

    var data = {'ecard_id': ecard_id};
    
    if($('#id_your_name').length) {
        data.from_name = $('#id_your_name').val();
    }
    
    if($('#id_message').length) {
        data.message = $('#id_message').val();
    }

    var url = global_locale_prefix + '/ajax/preview_ecard/?' + $.param(data);

    $('#ecard-modal').html(
        '<div style="text-align: right; padding-bottom: 15px;">' +
        '    <a href="javascript:kill_modal();">' +
        '        <img src="' + MEDIA_URL + 'img/x-button.png"' +
        '             alt="close"/>' +
        '    </a>' +
        '</div>' +
        '<iframe id="card-frame" src="' + url + '" marginheight="0" marginwidth="0" scrolling="no" width="700" height="400" style="padding:0;margin:0;"></iframe>'
    )
    $('#ecard-modal').jqmShow();
    
    //$.get(global_locale_prefix + '/ajax/preview_ecard/', data, function(response_data) {
    //    $('#ecard-modal-content').html(response_data);
    //    $('#ecard-modal').jqmShow();
    //});
}

//------------------------------------------------
// KinderHits
//------------------------------------------------

function get_kinderhits(options) {
    if(typeof(options.kh_download_type) != 'undefined') {
        kh_download_type = options.kh_download_type;
    }

    if(typeof(options.kh_range_type) != 'undefined') {
        kh_range_type = options.kh_range_type;
    }

    var request_data = {
        download_type: kh_download_type,
        range_type: kh_range_type
    }
    
    $.get(global_locale_prefix + '/ajax/kinder_hits/', request_data, function(response_data) {
        $('#kinderhits-tab-content').html(response_data);
    });
}

function setup_classcode_tip() {
    //------------------------------------------------
    // Set up ISBN / class code hints
    //------------------------------------------------

    $('#hint_id_class_code').append(' <a id="class-code-info" href="javascript:void(0);">' + gettext('Forgot your class code?  Click here to retrieve it.') + '</a>');
    $('#class-code-info').qtip({
        show: 'click',
        content: gettext('Please use the ISBN from one of your class books as your class code. You will find the ISBN on either the back or the inside front cover of each book.'),
        style: {
            name: 'blue',
            color: '#333',
            lineHeight: '14px'
        },
        position: {
            corner: {
                target: 'topMiddle',
                tooltip: 'bottomMiddle'
            }
        }
        
    });

}
