/***********************
 Required libraries:
 - jQuery
 - jQuery.cookie
 - jQuery.modal
 - jQuery.tweet
***********************/

var CTS;
if (CTS == undefined || CTS === null) {
    CTS = {
        Init : {
            quantity : function(q0name, q1name, tSame, tDiff) { // init quatity section
                var separate = jQuery('#quantity div:nth-child(2), #quantity div:nth-child(3)');
                var same = jQuery('#quantity div:nth-child(4)');
                var link = jQuery('#quantity span.jslink');
                var cpq0 = jQuery('input[name=' + q0name + ']');
                var cpq1 = jQuery('input[name=' + q1name + ']');
                var q0 = jQuery('input[name=qty0]');
                var q1 = jQuery('input[name=qty1]');
                var qb = jQuery('input[name=qty_both]');
                var validate = function(value) {
                    var v = parseInt(value, 10);
                    return isNaN(v) ? 1 : v;
                };
                var updateFromDifferent = function() {
                    qb.val(validate(jQuery(this).val()));
                    var v0 = validate(q0.val());
                    var v1 = validate(q1.val());
                    q0.val(v0);
                    q1.val(v1);
                    cpq0.val(v0);
                    cpq1.val(v1);
                };
                var updateFromSame = function() {
                    var v = validate(qb.val());
                    qb.val(v);
                    cpq0.val(v);
                    cpq1.val(v);
                };
                var showDifferentQty = function() {
                    separate.show();
                    same.hide();
                    link.text(tSame);
                    var v = validate(qb.val());
                    q0.val(v);
                    q1.val(v);
                    var v0 = validate(q0.val());
                    var v1 = validate(q1.val());
                    q0.val(v0);
                    q1.val(v1);
                    cpq0.val(v0);
                    cpq1.val(v1);
                };
                var showSameQty = function() {
                    separate.hide();
                    same.show();
                    link.text(tDiff);
                    var v = validate(qb.val());
                    cpq0.val(v);
                    cpq1.val(v);
                };
                link.toggle(showDifferentQty, showSameQty);
                qb.change(updateFromSame);
                q0.change(updateFromDifferent);
                q1.change(updateFromDifferent);
            },
            sizes : function(pid1, pid2) {
                var foo = function(pid) {
                    jQuery(function() {
                        var mw = jQuery('#modalWindowSize');
                        mw.jqm().jqDrag('.jqmTitle').jqResize('.jqResize');
                        jQuery('#sizechart_' + pid).click(function(e) {
                            e.preventDefault();
                            jQuery('iframe.jqmContent', mw).html('').attr('src', jQuery(this).attr('href'));
                            jQuery('.jqmTitleText', mw).text(jQuery(this).attr('title'));
                            jQuery('#modalWindowSize').jqmShow();
                            return false;
                        });
                    });
                };
                foo(pid1);
                foo(pid2);
                jQuery("div.size a.help").addClass('jslink');
            },
            notes : function(pid1, pid2) {
                var foo = function(pid) {
                    jQuery(function() {
                        jQuery('#modalWindow_' + pid).jqm().jqDrag('.jqmTitle').jqResize('.jqResize');
                        jQuery('#fithelp_' + pid).click(function(e) {
                            e.preventDefault();
                            jQuery('iframe#jqmContent_' + pid).html('').attr('src', jQuery(this).attr('href'));
                            jQuery('#jqmTitleText_' + pid).text(jQuery(this).attr('title'));
                            jQuery('#modalWindow_' + pid).jqmShow();
                            return false;
                        });
                    });
                };
                foo(pid1);
                foo(pid2);
                jQuery("div.fit a.help").addClass('jslink');
            }

        },
        Product : function(id) {
            var pid = '#product_' + id;
            var p = {
                id: id,
                price: 0,
                priceDifference: [],
                imageUrls: []
            };
            p.init = function() {
                var priceSpan, us, colors, colorList, sizeSelect, colorId, selectedColorId, selectedSize;
                priceSpan = $('.price span', pid);
                us = function() {
                    priceSpan.text(p.price + p.priceDifference[$(this).val()]);
                    $.cookie(this.id, this.selectedIndex);
                };
                sizeSelect = $('select', pid + '_size').change(us).keypress(us);

                colorList = $('ul', pid + '_color');
                colors = $('a', pid + '_color');
                colors.click(function(e) {
                    e.preventDefault();
                    colors.removeClass('selected');
                    $(this).addClass('selected');
                    colorId = $(this).attr('colorId');
                    $('img', pid + ' .image').attr("src", p.imageUrls[colorId].src);
                    $('input', pid + '_color').val(colorId);
                    // save color cookie
                    if (colorList.length) { $.cookie(colorList[0].id, colorId); }
                    return false;
                });

                // select last selected color
                selectedColorId = colorList.length && $.cookie(colorList[0].id);
                $(selectedColorId ? ('a[colorId=' + selectedColorId + ']') : 'a:first', pid + '_color').click();

                // select last selected size
                selectedSize = $.cookie(sizeSelect[0].id);
                if (selectedSize && sizeSelect.length) {
                    sizeSelect[0].options[parseInt(selectedSize, 10)].selected = true;
                    sizeSelect.change();
                }
                return p;
            };
            return p;
        },
        Feedback : function() {
            var fb, ff, toggle;
            fb = $('#feedback');
            ff = $('.form form div', fb);
            toggle = function() {
                var toggle = false, hide, show;
                hide = function() { ff.slideUp(); fb.animate({ left: '-170px' }, 500); };
                show = function() { ff.slideDown(); fb.animate({ left: '0px' }, 500); };
                return function() { toggle = !toggle; if (toggle) { show(); } else { hide(); } };
            }();
            $('.tab', fb).click(toggle);
            $('button', fb).click(function() {
                var b = this, f = b.form;
                b.disabled = true;
                $.post(f.action, $(f).serialize(), function(data) {
                    var m = $('.message', fb);
                    if (data.message) { m.html(data.message).show(); ff.slideUp(); }
                    setTimeout(data.success ? function() {
                        b.disabled = false;
                        toggle();
                        f.reset();
                        f.message.value = '';
                        m.hide();
                    } : toggle, 3000);
                }, 'json');
            });
            ff.hide();
            fb.removeClass('hide');
        }
    };
}

/* reads data to avoid XSS, potentially unsafe string that cannot be safely encoded for JavaScript */
(function($) {
    $.readData = function(s) {
        var r = {},n = "";
        $(s).children().each(function(i) {
            if (i % 2) {r[n] = $(this).text();}
            else {n = $(this).text();}
        }).remove();
        $(s).remove();
        return r;
    };

    $.modalFooter = function(selector, msgClose) {
        var s = jQuery(selector);
        var mw = jQuery('<div id="modalWindowFooter" class="jqmWindow"></div>');
        mw.append('<div class="jqmTitle jqDrag"><button class="jqmClose">' + msgClose + '&nbsp;X</button><span class="jqmTitleText">Title of modal window</span></div><iframe class="jqmContent" src=""></iframe><div class="jqResize"></div>');
        mw.jqm().jqDrag('.jqmTitle').jqResize('.jqResize');
        s.append(mw);
        jQuery('.modal', s).click(function(e) {
            e.preventDefault();
            jQuery('iframe.jqmContent', mw).html('').attr('src', jQuery(this).attr('href'));
            jQuery('.jqmTitleText', mw).text(jQuery(this).text());
            jQuery('#modalWindowFooter').jqmShow();
            return false;
        });
    };

    $.fn.tagcloud = function(scale, percentClassPrefix, keepFreq, overwriteCss) {
        var list = $('li', this);
        // overwrite CSS
        list.css(jQuery.extend({}, overwriteCss));
        var max = 0, min = 0;
        var getTagFrequency = function(x) {
            var matchs = x.text().replace(/\n/g, '').match(/\s*\d+\s*/g);
            if (!matchs) { return 0; }
            var freq = parseInt(matchs[matchs.length - 1], 10);
            return freq > 0 ? freq : 0;
        };
        //First pass : calc max and min
        list.each(function () {
            //extract and parse frequency
            freq = getTagFrequency($(this));
            //Calc max and min
            if (freq > max) { max = freq; }
            if (freq < min || min === 0) { min = freq; }
        });
        //Second pass : calc percent
        list.each(function () {
            //extract and parse frequency
            freq = getTagFrequency($(this));
            // Remove tags frequency ?
            if (!keepFreq) { $(this).html($(this).html().replace(/\n/g, '').replace(/\(\s*\d+\s*\)/g, '')); }
            //Calc percentage
            var percent = Math.ceil(((freq - min + 1) / (max - min + 1)) * scale);
            $(this).attr('class', percentClassPrefix + percent);
        });
    };

    $.advancedSearch = function() {
        $(document).ready(function() {
            var f = $("#advsearch");
            var qand = $('#qand');
            var qor = $('#qor');
            var qnot = $('#qnot');
            var button = $('#submit');
            var validate = function() {
                if (!qand.val() && !qor.val()) {
                    qand.addClass('error');
                    qor.addClass('error');
                    if (qnot.val()) {
                        qnot.removeClass('error');
                    }
                    else {
                        qnot.addClass('error');
                    }
                    button.attr("disabled", "true");
                    return false;
                }
                else {
                    qand.removeClass('error');
                    qor.removeClass('error');
                    qnot.removeClass('error');
                    button.removeAttr("disabled");
                }
                return true;
            };
            qand.blur(validate).keyup(validate);
            qor.blur(validate).keyup(validate);
            qnot.blur(validate).keyup(validate);
            f.submit(function() { return validate(); });
        });
    };
    $.fn.maxLength = function(max) {
        this.each(function() {
            //Get the type of the matched element
            var type = this.tagName.toLowerCase();
            //If the type property exists, save it in lower case
            var inputType = this.type ? this.type.toLowerCase() : null;
            //Check if is a input type=text OR type=password
            if (type == "input" && inputType == "text" || inputType == "password") {
                //Apply the standard maxLength
                this.maxLength = max;
            }
            //Check if the element is a textarea
            else if (type == "textarea") {
                //Add the key press event
                this.onkeypress = function(e) {
                    //Get the event object (for IE)
                    var ob = e || event;
                    //Get the code of key pressed
                    var keyCode = ob.keyCode;
                    //Check if it has a selected text
                    var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                    //return false if can't write more
                    return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode === 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
                };
                //Add the key up event
                this.onkeyup = function() {
                    //If the keypress fail and allow write more text that required, this event will remove it
                    if (this.value.length > options.max) {
                        this.value = this.value.substring(0, max);
                    }
                };
            }
        });
        return this;
    };
    $.fn.charsRemaining = function(max, text) {
        this.each(function() {
            //Check if the element is a textarea
            if (this.tagName.toLowerCase() == "textarea") {
                var tam = $('<span class="textareamessage"></span>');
                $(this).after(tam);
                tam.html(text.replace('##', max - this.value.length));
                this.onkeyup = function() {
                    tam.html(text.replace('##', max - this.value.length));
                };
            }
        });
        return this;
    };
})(jQuery);

// application scope
jQuery(document).ready(function() {
    $("#spinner").bind("ajaxSend", function() { $(this).show(); }).bind("ajaxComplete", function() { $(this).hide(); });
    $('a[rel=external]').click(function() { this.target = "_blank"; });
    var lInner = $('#topLoginBoxInner');

    // TODO check if lInner exists, if not dont' do the rest

    var lUsername = $('#topLoginUsername');
    var fUsername = $('#topUsername');
    var lOpenID = $('#topLoginOpenID');
    var fOpenID = $('#topOpenID');
    $('a.login').toggle(
            function() { lInner.slideDown('fast', function() { fUsername.focus(); }); },
            function() { lInner.slideUp('fast'); });
    $('#loginSwitchOpenID').click(function() {
        lInner.slideUp('normal', function() {
            lUsername.hide();
            lOpenID.show();
            fOpenID.focus();
            lInner.slideDown('fast');
        });
    });
    $('#loginSwitchUsername').click(function() {
        lInner.slideUp('normal', function() {
            lOpenID.hide();
            lUsername.show();
            fUsername.focus();
            lInner.slideDown('fast');
        });
    });
});
