var hmpg_panels_head_timer = null;
var hmpg_panels_timer = null;
var pg_images_count = 0;
var rp_count = 0;
var default_alert_timeout = 4000;

function __(msgid) {
    if (typeof(locale[msgid]) == 'undefined') {
        if (msgid.substring(0,3) == 'JS_') {
            return msgid.substring(3);
        } else {
            return msgid;
        }
    } else {
        return locale[msgid];
    }
}

//ajax nastavenia
$.ajaxProgress.setImage(WEBROOT + '/public/images/loading.gif');
$(function () {
    $("#ajaxProgress").ajaxStart(function () {
        var scrollXY = getScrollXY();
        $(this).css({
            top: scrollXY[1],
            right: '0px'
        }).show(0);
    }).ajaxStop(function () {
        $(this).hide(0);
        $(this).text(__('loading...'));
    });
});

var Router = {
    getRoute: function (r,params) {
        var url = LANGROOT + '/' + r;
        if (params) {
            url += '?';
            $.each(params,function (name,value) {
                url += escape(name) + '=' + escape(value) + '&';
            });
        }
        return url;
    }
}

function ViewImage() {
    
}

//ajax default nastavenia
$.ajaxSetup({
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert(textStatus);
    }
});

//plugin na zebra tabulky
jQuery.fn.zebraTable = function () {
    this.each(function () {
        var self = $(this);
        if (self.is('table')) {
            $('tbody tr:even',self).removeClass('even').addClass('odd');
            $('tbody tr:odd',self).removeClass('odd').addClass('even');
        }
    });
    return this;
};
//plugin na highlight tabulky
jQuery.fn.highlightTable = function () {
    this.each(function () {
        var self = $(this);
        if (self.is('table')) {
            $('tbody tr',self).unbind('mouseover.highlight').bind('mouseover.highlight',function () {
                $('>td',this).addClass('highlight');
            });
            $('tbody tr',self).unbind('mouseout.highlight').bind('mouseout.highlight',function () {
                $('>td',this).removeClass('highlight');
            });
        }
    });
    return this;
};

jQuery.fn.stroboskop = function () {
    this.fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200); //.fadeOut(200).fadeIn(200).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
    return this;
}

$(function () {
    //zebra tabulky - bez highlight
    $('table.zebra').zebraTable();
    $('table.highlight').highlightTable();
    
    $('.galleryImage', '#pg_list').each(function (idx, el) {
        pg_images_count++;
    });
    
    $('#pgMoveLeft').click(function () {
        movePgImages('prev');
    });
    
    $('#pgMoveRight').click(function () {
        movePgImages('next');
    });
    
    $('.relatedProduct', '#rp_list').each(function (idx, el) {
        rp_count++;
    });
    
    $('#rpMoveLeft').click(function () {
        moveRelatedProducts('prev');
    });
    
    $('#rpMoveRight').click(function () {
        moveRelatedProducts('next');
    });
    
    // prihlasenie
    $('a.login').click(function () {
        var dialogContent = new Dialog.content({
            url: Router.getRoute('account/login-form/')
        });
        var dialog = new Dialog('loginDialog',{
            size: 'small',
            onShow: function (d) {
                d.center();
                if (typeof(load_callback) == 'function') {
                    load_callback();
                }
                if (typeof(callback) == 'function') {
                    callback();
                }
            },
            onContentLoad: function (d) {
                d.center();
                
                $('#bpLoginFormCancel').click(function () {
                    d.close();
                });
                
                $('#bpLoginFormSubmit').click(function () {
                    var login = $('#dl_login').val();
                    var passw = $('#dl_password').val();
                    $.post(Router.getRoute('account/login/'), {
                        login: login,
                        passwd: passw
                    }, function (data) {
                        var data2 = data.split('!@#$');
                        if (data2[0] == 'ERROR') {
                            Alert(data2[1]);
                        } else if (data2[0] == 'LOGGED') {
                            Alert(data2[1]);
                        } else {
                            $('#top .account').html(data);
                            d.close();
                            $('#top .account').stroboskop();
                            
                            reloadPanelCart();
                            reloadTopCart();
                            reloadTopCartHead();
                        }
                    });
                });
                
                $('#lostPassword').click(function () {
                    var passwdDialogContent = new Dialog.content({
                        url: Router.getRoute('registration/lost-password/')
                    });
                    var passwdDialog = new Dialog('passwdDialog', {
                        size: 'login',
                        onShow: function (d2) {
                            d2.center();
                        },
                        onContentLoad: function (d2) {
                            d2.center();
                            
                            $('#bpLostpasswordFormCancel').click(function () {
                                d2.close();
                            });
                            
                            $('#submitLostpasswordForm').click(function () {
                                var dl_email = $('#dl_email').val();
                                if (dl_email != '') {
                                    $.getJSON(Router.getRoute('registration/lost-password/'), {
                                        email: dl_email
                                    }, function (json) {
                                        d2.close();
                                        if (json.error) {
                                            Alert(json.error);
                                        } else if (json.ok) {
                                            Alert(json.ok, true, default_alert_timeout);
                                        }
                                    });
                                }
                            });
                        },
                        content: passwdDialogContent
                    });
                    passwdDialog.show();
                });
                
            },
            content: dialogContent
        });
        dialog.show();
    });
    
    // pridanie produktu do kosika
    $('a.addToCart').click(function () {
        clearCycle();
        var self = $(this);
        $.getJSON(Router.getRoute('account/is-logged/'), function (json) {
            if (json.logged == 1) {
                var product_id = $(self).attr('rel');
                var count = $('.cart_count_' + product_id).val();
                
                addToCart(product_id, count);
                
                // window.location.href = Router.getRoute('voip-eshop/add-to-cart/pid/' + product_id + '/cnt/' + count + '/');
                // return false;
            } else {
                var dialogContent = new Dialog.content({
                    url: Router.getRoute('account/add-to-cart/')
                });
                var dialog = new Dialog('addtocartDialog', {
                    size: 'cart',
                    onShow: function (d) {
                        d.center();
                    },
                    onContentLoad: function (d) {
                        d.center();
                        
                        $('#bpLoginFormCancel').click(function () {
                            d.close();
                        });
                        
                        $('#bpLoginFormSubmit').click(function () {
                            var login = $('#dl_login').val();
                            var passw = $('#dl_password').val();
                            $.post(Router.getRoute('account/login/'), {
                                login: login,
                                passwd: passw
                            }, function (data) {
                                var data2 = data.split('!@#$');
                                if (data2[0] == 'ERROR') {
                                    Alert(data2[1]);
                                } else if (data2[0] == 'LOGGED') {
                                    Alert(data2[1]);
                                } else {
                                    $('#top .account').html(data);
                                    d.close();
                                    $('#top .account').stroboskop();
                                    
                                    var product_id = $(self).attr('rel');
                                    var count = $('.cart_count_' + product_id).val();
                                    
                                    addToCart(product_id, count);
                                }
                            });
                        });
                        
                        
                        $('#lostPassword').click(function () {
                            var passwdDialogContent = new Dialog.content({
                                url: Router.getRoute('registration/lost-password/')
                            });
                            var passwdDialog = new Dialog('passwdDialog', {
                                size: 'login',
                                onShow: function (d2) {
                                    d2.center();
                                },
                                onContentLoad: function (d2) {
                                    d2.center();
                                    
                                    $('#bpLostpasswordFormCancel').click(function () {
                                        d2.close();
                                    });
                                    
                                    $('#submitLostpasswordForm').click(function () {
                                        var dl_email = $('#dl_email').val();
                                        if (dl_email != '') {
                                            $.getJSON(Router.getRoute('registration/lost-password/'), {
                                                email: dl_email
                                            }, function (json) {
                                                d2.close();
                                                if (json.error) {
                                                    Alert(json.error);
                                                } else if (json.ok) {
                                                    Alert(json.ok, true, default_alert_timeout);
                                                }
                                            });
                                        }
                                    });
                                },
                                content: passwdDialogContent
                            });
                            passwdDialog.show();
                        });
                        
                    },
                    content: dialogContent
                });
                dialog.show();
            }
        });
    });
    
    $('.report').each(function (idx, el) {
        $(el).remove();
        var report_text = $(el).html();
        report_text = report_text.replace('<span class="ico ico_ERROR">&nbsp;</span>', '');
        if ($(el).is('.report_OK')) {
            Alert(report_text, true, default_alert_timeout);
        } else {
            Alert(report_text);
        }
    });
});

function movePgImages(direction) {
    var gallery_image_width = 125;
    var left = parseInt($('#pg_list').css('left'), 10);
    
    if (direction == 'prev') {
        if (left < 0) {
            var new_left = left + gallery_image_width;
            $('#pg_list').animate({
                left: '+=' + gallery_image_width + 'px'
            }, 'slow');
        }
    }
    if (direction == 'next') {
        if (left > -1 * ((pg_images_count - 4) * gallery_image_width)) {
            var new_left = left - gallery_image_width;
            $('#pg_list').animate({
                left: '-=' + gallery_image_width + 'px'
            }, 'slow');
        }
    }
}

function moveRelatedProducts(direction) {
    var related_product_width = 125;
    var left = parseInt($('#rp_list').css('left'), 10);
    
    if (direction == 'prev') {
        if (left < 0) {
            var new_left = left + related_product_width;
            $('#rp_list').animate({
                left: '+=' + related_product_width + 'px'
            }, 'slow');
        }
    }
    if (direction == 'next') {
        if (left > -1 * ((rp_count - 4) * related_product_width)) {
            var new_left = left - related_product_width;
            $('#rp_list').animate({
                left: '-=' + related_product_width + 'px'
            }, 'slow');
        }
    }
}

function clearCycle() {
    // vynulovanie timerov
    window.clearInterval(hmpg_panels_head_timer);
    window.clearInterval(hmpg_panels_timer);
    hmpg_panels_head_timer = null;
    hmpg_panels_timer = null;
}

function addToCart(product_id, count) {
    $.getJSON(Router.getRoute('voip-eshop/add-to-cart/'), {
        pid: product_id,
        cnt: count
    }, function (json) {
        if (json.error) {
            Alert(json.error);
        } else if (json.cartSummary) {
            $('#topCartCount').text(json.cartSummary.count);
            $('#topCartPrice').text(json.cartSummary.price);
            reloadTopCartHead();
            $('#top .cart').stroboskop();
            
            reloadPanelCart();
        }
        if (json.message) {
            Alert(json.message, true, default_alert_timeout);
        }
    });
}

function reloadTopCartHead() {
    var text = $('#topCartHead').text();
    var url = Router.getRoute('voip-eshop/cart/');
    $('#topCartHead').empty().append('<a href="' + url + '">' + text + '</a>');
}

function reloadPanelCart() {
    $('#panel_cart').ajaxProgress();
    $('#panel_cart').load(Router.getRoute('voip-eshop/right-panel-cart/'));
    $('#panel_cart').stroboskop();
}

function reloadTopCart() {
    $.getJSON(Router.getRoute('voip-eshop/cart-summary/'), function (json) {
        if (json.cartSummary) {
            $('#topCartCount').text(json.cartSummary.count);
            $('#topCartPrice').text(json.cartSummary.price);
            $('#top .cart').stroboskop();
        }
    });
}

var Alert_counter = 0;
Alert = function (msg, overlay, timeout, callback) {
    if (overlay != false) {
        overlay = true;
    }
    Alert_counter++;
    var dialogContent = new Dialog.content({
        html: msg
    }).addButton(__('JS_OK'),function (d) {
        d.close();
        var ret = true;
        if (typeof(callback) == 'function') {
            ret = callback();
        }
    });
    var dialog = new Dialog('alert' + Alert_counter,{
        size:'login',
        onShow: function (d) {
            d.center();
        },
        content: dialogContent,
        overlay: overlay
    });
    dialog.show();
    if (typeof(timeout) != 'undefined' && timeout != null) {
        window.setTimeout(function () {
            dialog.close();
        }, timeout);
    }
}

var Confirm_counter = 0;
Confirm = function (msg, fcnYes, fcnNo) {
    Confirm_counter++;
    var dialogContent = new Dialog.content({
        html: msg
    }).addButton(__('JS_Yes'), function (d) {
        d.close();
        var ret = true;
        if (typeof(fcnYes) == 'function') {
            ret = fcnYes();
        }
    }).addButton(__('JS_No'), function (d) {
        d.close();
        var ret = true;
        if (typeof(fcnNo) == 'function') {
            ret = fcnNo();
        }
    });
    var dialog = new Dialog('confirm' + Confirm_counter, {
        size: 'small',
        onShow: function (d) {
            d.center();
        },
        content: dialogContent
    });
    dialog.show();
}
