var Items = {};
var Bookmark = {};
var locale = location.pathname.split('/')[1];


/* IE sucks big time */
    document.createElement('header');
    document.createElement('footer');
    document.createElement('section');
    document.createElement('aside');
    document.createElement('nav');
    document.createElement('article');
    document.createElement('figure');
    document.createElement('time');

/* simple cross-browser script for adding a bookmark
    source: http://stackoverflow.com/questions/992844/add-to-browser-favourites-bookmarks-from-javascript-but-for-all-browsers-mine-do
*/
function addToFavorites(url, name) {
    if (window.sidebar) { // Mozilla Firefox
        window.sidebar.addPanel(name, url, "");
    } else if (window.external) { // IE
        window.external.AddFavorite(url, name);
    } else {
        alert("Sorry! Your browser doesn't appear to support this function.");
    }
} 

function html_entity_decode(str) {
    var ta=document.createElement("textarea");
    ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
    return ta.value;
}

$(document).ready(function()
{
    if ($('input.datetimepicker').length) {
        $('input.datetimepicker').datetimepicker(
        {
            duration: '',
            changeMonth: true,
            changeYear: true,
            yearRange: '2009:2020',
            showTime: true,
            time24h: true,
            closeText: 'OK'
        });
        $('input.datetimepicker').css({
            'background': "transparent url('/www/images/calendar.png') no-repeat right"
        })
    }

    $("#tabs").tabs();
    $("#tabs").bind('tabsshow',function(event, ui) { /*http://chwang.blogspot.com/2010/02/jquery-ui-tabs-updating-url-with-hash.html*/
        window.location = ui.tab;
    })
    $('form').attr('novalidate', true);

    canonicalizeTabHeight();

    activateEmails();
    
    url = "/"+locale+"/api/"
    orderform = $(".orderform");
    if (orderform.length > 0) {
        orderform.removeAttr('novalidate');
        if (!($.browser.msie && parseInt($.browser.version, 10) < 7)) {
            $('#loader')
            .ajaxStart(function() {
                $(this).append('<span id="img-ajax-loader"></span>')
            })
            .ajaxStop(function() {
                $('#img-ajax-loader', this).remove();
                $('.orderform', this).slideDown(750);
            //$('#invoicing-information').toggle();
            });

            it = $.getJSON(url, null, initItems);
        }
    }
    
    $("a[rel^='prettyPhoto']").prettyPhoto({
	overlay_gallery: false,
        changepicturecallback: function(){
                $('.pp_savePhotoLink').remove();
                linktext = (locale == 'cs' ? 'Uložit fotografii' : 'Download photo');
                href = $('#fullResImage').attr('src').split('/');
                realhref = href[href.length-1];
                $('.pp_nav').append('<a class="pp_savePhotoLink" href="fetch?file='+ realhref +'">'+ linktext +'</a>')
            }
	});

    // chrome does not permit addToFavorites() function by design
    Bookmark.title = (locale == 'cs' ? 'Lehatko.cz - Objednávka' : 'Lehatko.cz - Order');
    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1 || window.opera) {
        $('.addbookmark').attr({
            //href: 'javascript:return false;'
            })
        .css({
            opacity: .25
        });       // dim the button/link
    }

});

function initItems(data) {
    Items.data = data;
    Items.displayed = 0;
    Items.total = 0;
    Items.summaryrow = $('#summaryrow');

    // show form
    Items.appendShippingRow();
    Items.shippingrow = $('#shippingrow');
    Items.prepareCurrentDataWrapper();

    $('#addRowButton').click(function() {
        Items.appendRow(null, null, true);
    });
// activate toggle
//    $('#invoice-toggle').click(function() {
//       $('#invoicing-information').toggle();
//    });

}

Items.prepareCurrentDataWrapper = function() {
    url = "/"+locale+"/api/current/"
    $.getJSON(url, null, Items.prepareCurrentData)
}

Items.prepareCurrentData = function(data) {
    Items.current = data.items;
    if (Items.current == undefined) {
        Items.current = [];
    }
    if (typeof console !== 'undefined') {
        console.log('Session data ready ('+ Items.current.length +')');
    }
    input = $(document.createElement('input'));
    input.attr({
        type: 'hidden',
        name: 'shipping',
        id: 'shipping',
        value: '0'
    })
    $('.orderform').append(input);
    if (data.length == 0) { // no session data, create deafult input
        Items.appendRow();
        Items.recountRows();
    } else {
        // id, quantity, accessory
        $.each(Items.current, function() {
            if (!this.quantity) {
                qty = 1;
            } else {
                qty = this.quantity;
            }
            current = Items.appendRow(this.id, qty);
        });
        Items.recountRows();
    }

    // data - other fields
    $('#frmorderForm-ship_name').val(data.ship_name);
    $('#frmorderForm-ship_ic').val(data.ship_ic);
    $('#frmorderForm-ship_dic').val(data.ship_dic);
    $('#frmorderForm-ship_street').val(data.ship_street);
    $('#frmorderForm-ship_city').val(data.ship_city);
    $('#frmorderForm-ship_zipcode').val(data.ship_zipcode);
    if (data.ship_country !== undefined) {
        $('#frmorderForm-ship_country').val(data.ship_country);
    }

    $('#frmorderForm-inv_name').val(data.inv_name);
    $('#frmorderForm-inv_ic').val(data.inv_ic);
    $('#frmorderForm-inv_dic').val(data.inv_dic);
    $('#frmorderForm-inv_street').val(data.inv_street);
    $('#frmorderForm-inv_city').val(data.inv_city);
    $('#frmorderForm-inv_zipcode').val(data.inv_zipcode);
    if (data.inv_country !== undefined) {
        $('#frmorderForm-inv_country').val(data.inv_country);
    }

    $('#frmorderForm-email').val(data.email);
    $('#frmorderForm-phone').val(data.phone);

}

Items.appendShippingRow = function() {
    tr = $(document.createElement('tr'));
    tr.attr('id', 'shippingrow');
    input = '';

    td = $(document.createElement('td'));
    td.attr('colspan', '3');
    if (locale == 'cs') {
        td.text('Poštovné a balné (platí pouze pro ČR)');
    } else {
        td.text('Shipping and packaging (Fees are valid for Czech republic and may change)');
    }

    tr.append(td);

    td = $(document.createElement('td'));
    td.append('<span id="shipping-cost">0</span>');
    tr.append(td);

    td = $(document.createElement('td'));
    tr.append(td);

    $('#summaryrow').before(tr);
}

Items.appendRow = function(selected, quantity, refresh) {
    Items.shippingrow.before(Items.makeRow(selected, quantity));
    Items.displayed++;
    Items.total++;
    if (refresh) {
        Items.recountRows();
    }
    return Items.total-1;
}

Items.addRowAfter = function(rownr, norefresh) {
    $('#items-row-'+rownr).after(Items.makeRow());
    Items.displayed++;
    Items.total++;
    return Items.total-1;
}

Items.setDeleteAction = function() {
    $.each($(".item-row"), function() {
        var row = this;
        $('.delete-row', this).click(function() {
            $(row).hide();
            $('.quantity', row).val(0);
            Items.recountRows();
        });
    });
}


Items.recountRows = function() {
    rows = $('.item-row');
    totalrowprice = 0;
    inversionTablesCount = 0;
    $.each(rows, function() { // row prices
        rowid = Number( $(this).attr('id').split('-')[2] );
        qty = $('input', this).val();

        if (qty == 0) {
            $('#items-row-'+rowid).remove();
            Items.displayed--;
            if (Items.displayed == 0) {
                Items.appendRow();
                Items.recountRows();
            }
            return;
        }

        productId = $('select', this).val();
        realprice = qty * Items.data[productId].price;
        rowprice = $('span', this);
        rowprice.text(realprice + ' CZK');
        totalrowprice += realprice;

        // color
        selected = $('#color-'+rowid+' select').val();
        if (!selected && Items.current[rowid]) {
            selected = Items.current[rowid].color;
        }
        $('#color-'+rowid).append(Items.testAndMakeColorSelect(rowid, productId, selected));

        if (Items.data[productId].accessory === '0') {
            inversionTablesCount += parseInt(qty);
        }
    });

    if (inversionTablesCount == 0) {
        packprice = 120;
    } else {
        packprice = 400*inversionTablesCount;
    }

    nfobox = $('#shipping-cost');
    newprice = packprice + ' CZK';
    nfobox.text(newprice);
    $('#totalprice', Items.summaryrow).text(totalrowprice + packprice + ' CZK');
    $('#shipping').val(packprice);
    Items.setDeleteAction();
}

Items.makeRow = function(selected, quantity){
    colorSelected = 7;
    rownr = Items.total;
    tr = $(document.createElement('tr'));
    tr.attr({
        id: 'items-row-'+rownr
    });
    tr.addClass('item-row');
    input = '';

    td = $(document.createElement('td'));
    td.append(Items.makeSelect(rownr, selected));
    td.append(input);
    tr.append(td);

    td = $(document.createElement('td'));
    td.attr({
        id : 'color-' + rownr
    })
    tr.append(td);

    td = $(document.createElement('td'));
    td.append(Items.makeQuantity(rownr, quantity));
    tr.append(td);


    td = $(document.createElement('td'));
    td.append('<span id="items['+rownr+'][price]">0</span>');
    tr.append(td);

    td = $(document.createElement('td'));
    td.addClass('delete-cell');
    td.append('<a class="icon icon-delete delete-row"><span>X</span></a>');
    tr.append(td);

    return tr;
}

Items.testAndMakeColorSelect = function(rownr, productId, selected) {
    $('#color-'+rownr+' select').remove();
    if (Items.data[productId].colors.length == 0) {
        return '';
    }

    select = $(document.createElement('select'));
    select.attr({
        id: 'items['+rownr+'][color]',
        name: 'items['+rownr+'][color]'
    });

    dat = Items.data[productId].colors;

    $.each(dat, function(id, data) {
        option = $(document.createElement('option'));
        option.attr('value', id);
        option.text(data.name);
        if (selected && selected == id) {
            option.attr('selected', 'selected');
        } else {
            option.removeAttr('selected');
        }
        select.append(option);
    });

    return select;
}

Items.makeQuantity = function(rownr, quantity) {
    input = $(document.createElement('input'));
    input.attr({
        id: 'items['+rownr+'][quantity]',
        name: 'items['+rownr+'][quantity]',
        'class': 'quantity'
    });
    if (!quantity) {
        input.val('1');
    } else {
        input.val(quantity);
    }

    input.change(Items.recountRows);
    return input;
}

Items.makeSelect = function(rownr, selected) {
    if (!selected) {
        $.each(Items.data, function(id, data) {
            if (data.isDefault === '1') {
                selected = id;
            }
        })
    }

    select = $(document.createElement('select'));
    select.attr({
        id: 'items['+rownr+'][id]',
        name: 'items['+rownr+'][id]'
    });

    dat = Items.data

    $.each(dat, function(id, data) {
        option = $(document.createElement('option'));
        option.attr('value', id);
        option.attr('title', html_entity_decode(data.description));
        if (data.display_name == "") {
            option.text(data.name);
        } else {
            option.text(data.name+" - "+data.display_name);
        }
        if (selected && selected == id) {
            option.attr('selected', 'selected');
        } else {
            option.removeAttr('selected');
        }
        select.append(option);
    });

    select.change(Items.recountRows);
    return select;
}


/**
 *
 */
function canonicalizeTabHeight() {
    var panels = $(".ui-tabs-panel");
    var max = 0;
    var hidden = false;
    for (i = 0; i < panels.length; i++) {
        panel = $(panels[i]);
        if (panel.hasClass('ui-tabs-hide')) {
            //panel.css({display: "block !important"});
            panel.removeClass('ui-tabs-hide');
            hidden = true;
        }
        if (panel.height() > max) {
            max = panel.height()
        }
        if (hidden) {
            //panel.css({display: ""});
            panel.addClass('ui-tabs-hide');
            hidden = false;
        }
    }
    panels.css({
        height: max+'px'
    });

}

function activateEmails() {
    var emails = $(".email");
    for (i = 0; i < emails.length; i++) {
        span = $(emails[i]);
        email = span.text();
        span.text('');
        revertedemail = email.split("").reverse().join("");
        span.append('<a href="mailto:' + revertedemail +'">' + email +'</a>')
    }
}

