﻿$(function () {
    $.address.change(function (event) {
        var page = event.value.split('?')[0].split('/').pop();
        var link = $('a[href$="' + page + '"][href*="#!"]'); // end with

        if (!link.length) {
            link = $('a[href*="' + page + '"][href*="#!"]'); // contains
        }

        // return on root
        if (event.value == '/' && $('#returnBack').is(':visible')) {
            ShowEventsInfo();
            $.address.title($('.header-panel img').attr("alt"));
            return;
        }

        var train = $('a[rel="' + page + '"]:first');

        if (train.length) {
            train.click();

            if ($('#returnBack').is(':visible')) {
                ShowEventsInfo();
                $.address.title($('.header-panel img').attr("alt"));
            }
            return;
        }

        if (event.value == '/') // IE7 bug
            return;

        if (link.length) {
            SetupLayout(link);

            var url = baseurl + page + ($(link).hasClass('aspx-page') ? '.aspx' : '.html');
            var title = $(link).attr("title");

            ShowProductInfo(url, title);

            $.address.title(title);

            $.scrollTo({ left: 0, top: 0 }, 600);
        }
    });

    FilterShop(0);

    // Tabs
    $('#tabs').tabs({
        show: OnShowTab,
        load: OnLoadTab,
        select: function (event, ui) {
            // Highlight date
            $('.event-date-active').removeClass('event-date-active');
            $('.event-date:eq(' + ui.index + ')').addClass('event-date-active');

            //            var selectedPanel = $("#tabs div.ui-tabs-panel:not(:has(.ui-tabs-hide))");
            var selected = $('#tabs').tabs('option', 'selected');

            $('#tabs > div:eq(' + selected + ')').append(GetLoader());
        },
        cookie: {
            // store cookie for a day, without, it would be a session cookie
            expires: 30
        },
        spinner: '',
        fx: { opacity: 'toggle' }
    }).removeClass('ui-corner-all').addClass('ui-corner-top');

    // Today product
    var prod_cnt = $('.prod:not([data-prod~="-1"])').length;

    RecomendProduct(Math.floor(Math.random() * prod_cnt));

    $('#Content').css('visibility', 'visible');

    var tabs = $('#tabs ul li a');
    var anounce = $('#anounce tr td:first').next();
    var totalWidth = 20;

    tabs.each(function (i) {
        var evtDates = GetEventDataArray(this, 'dates');
        var info = GetEventData(this, 'event');

        var headerDate = evtDates[0];

        var an = $('<td class="event-date">' + headerDate.replace("-", "&nbsp;&ndash;&nbsp;") + '</td>');

        if (i == $('#tabs').tabs('option', 'selected')) {
            an.addClass('event-date-active');
        }

        var wd = $(this).outerWidth(true) + 'px';

        an.css("width", wd).css("min-width", wd);

        an.insertBefore(anounce);

        totalWidth += $(this).outerWidth(true) + 4;
    });

    var wd = ($.browser.msie && parseInt($.browser.version) <= 6) ? 'width' : 'min-width';

    $('#tabs').css(wd, Math.max(670, totalWidth) + "px");

    var dt = new Date();
    $('#today').text(dt.toLocaleDateString());

    // Login
    SetupLogin();

    $('#SubscribEmail').watermark("электронная почта", { useNative: false });
    $("#FeedbackLinkImage").mouseover(st1).mouseout(cst).click(go1);

    // RSS cookie
    var rsscokie = new Array();
    $('.rss-preview a').each(function (ind) {
        var hash = $.cookie('rsslink' + ind, { path: '/' });
        rsscokie.push(hash != null ? hash.toString() : '');
    }).each(function (ind) {
        var hash = GetHash($(this).text());
        var vx = rsscokie.findIndex(hash.toString());
        var lnk = vx != -1 ? rsscokie[vx] : null;

        if (lnk == null) {
            $(this).after($('<sup>').text('новое'));
        }

        $.cookie('rsslink' + ind, hash, { expires: 3 });
    });
});

Array.prototype.findIndex = function (value) {
    var ctr = -1;
    for (var i = 0; i < this.length; i++) {
        // use === to check for Matches. ie., identical (===), ;
        if (this[i] == value) {
            return i;
        }
    }
    return ctr;
};

function GetHash(str) {
    var hash = 0;
    if (str.length == 0) 
        return hash;

    for (i = 0; i < str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    return hash;
}

function jSONtoArray(obj) {
    var vals = [];
    for (var key in obj) {
        vals.push(obj[key]);
    }
    return vals;
}
    
function FilterShop(code){
    var cnt = 0;

    $('#ShopDataList div').each(function() {
        var meta = $(this).data('prod');

        // Filter advert
        if (meta.owner == -1) {
            var row = $(this).parent();

            var part = $('<tr>').append(row.clone());

            part.appendTo('#Advert');

            row.remove();

            part.find('a').addClass('hide-shop');

            return;
        }

        if (meta.owner != code) {
            $(this).parent().hide();
        }
        else {
            $(this).parent().show();
            cnt++;
        }
    });
    
    // Show filtered products
    if (!$('#ShopDataList').data('showProducts'))
    {
        $('.product-item').show();
        $('#ShopDataList').data('showProducts', true);
    }    
    
    return cnt;   
};

function ShowProductInfo(page, title){
    // Navigation
    var an = $('#anounce tr:first');
    an.hide().next().show();
    //an.toggle();

    // Tabs
    $('#tabs').hide(); //hide
    
    // Old content
    $('#ProdContent').empty();
    $('#ProdDetails').show(); // show
    
    // Header
    $('#ProdHeader').text(title);

    // Load
    $.ajax({
        url: page,
        cache: true,
        beforeSend: function (xhr) {
            $('#ProdContent').append(GetLoader());
        },
        success: function (html) {
            $('#ProdContent .loader').remove();
            var d = $('#ProdContent').prepend(html);
            
            ResolveUrl(d);

            MakeExpandLink('.expandable');

            UpdateProdContact();

            UpdateProdPrice();

            // Video
            AppendVideo('video, audio');

            var titlearr = jSONtoArray($('#ProdContent #order-form').data('caption'));

            AppendOrderForm($('#ProdContent #order-form'), titlearr.length ? titlearr : [title], $('div.prod-selected').data('prod'));
        }
    });
};

function ShowEventsInfo() {
    // Remove Highlight header
    var prods = $('#ShopDataList, #Advert, #Recomend');
    prods.find('.ui-state-active, .prod-selected').removeClass('ui-state-active prod-selected');

    // Revert
    if ($('#Advert').data('visible'))
        $('#Advert').parent().show();

    $('#ShopDataList').show();

     // Navigation
    var an = $('#anounce tr:first');
    an.show().next().hide();

    // Old content
    $('#ProdDetails').hide(); //hide

    $('#ProdContent').children().remove();
 
    // Tabs
    var $tabs = $('#tabs').tabs();
    var selected = $tabs.tabs('option', 'selected');

    // Always reloads current tab content! To be optimized.
    $tabs.tabs('load', selected); // switch to selected tab

    $tabs.show();// show
}

function MakeExpandLink(id) {

    $(id).each(function () {

        if ($(this).find('.exp').length == 0) {
            $(this).removeClass('expandable');
            var v = $('<div class="exp ' + $(this).attr('class') + '"><a href="#" class="source-closed ajaxlink expandor"><span class="ui-icon ui-icon-triangle-1-e"></span></a><div class="expanded"></div></div>').insertBefore(this);

            v.find(">a").click(function () {
                $(this).toggleClass("source-closed").toggleClass("source-open").next().slideToggle();
                $(this).find("span").toggleClass('ui-icon-triangle-1-e')
                                    .toggleClass('ui-icon-triangle-1-s').next().toggle();
                return false;
            }).end().find('>div').hide();

            txt = v.find('a').html() + $(this).attr('title');

            v.find('a').html(txt);
            v.find('div').empty().html($(this).html());
        }

        $(this).remove();
    });
}

function AppendOrderForm(tag, title, meta) { 
  
    // Remove if any
    $('#OrderForm').unbind().remove();

    // Load order form
    $.ajax({
        url: baseurl + "OrderForm.html",
        cache: true,
        success: function (html) {
            var d = $('<div>').html(html);

            d.find('[src]').filter(':not([src^="http"])').each(function () {
                $(this).attr('src', baseurl + $(this).attr('src'));
            });

            d.find('link[href]').each(function () {
                $(this).attr('href', baseurl + $(this).attr('href'));
            });

            d.find('form[action]').each(function () {
                $(this).attr('action', baseurl + $(this).attr('action'));
            });

            tag.append(d.html());
            
            InitForm();
            
            SetupProduct(title, meta);

            if (IsAuth()) {
                $('.payment').show();
            }
        }
    });
}

function UpdateProdPrice() {
    var sel = $('div.prod-selected');

    if (sel.length) {
        var data = sel.data('prod');

        if (data.price) {
            UpdateAuthField($('.section-price'), data.price);
        }
    }
}

function UpdateProdContact() {
    var sel = $('div.prod-selected');

    if (sel.length) {
        var data = sel.data('prod');

        if (data.contact) {
            UpdateField($('.section-phone'), $('<span class="tel">').html(data.contact));
        }
    }
}

function UpdateAuthField(tag, cont) {
    if (IsAuth()) {
        UpdateField(tag, cont);
    }
    else {
        var reg = $('<span>Что-бы узнать цену <a href="' + baseurl + 'login" class="ajaxlink">войдите</a> или <a href="' + baseurl + 'register" class="ajaxlink">зарегиструриуйтесь</a>.</span>');

        UpdateField(tag, reg);
    }
}

function UpdateField(tag, cont) {
    if (!tag.length)
        return

    if (cont.length)
        tag.append($('<span>&nbsp;</span>')).after(cont);
    else
        tag.parent().remove();
}

function OnLoadTab(event, ui) {
    var evtDates = GetEventDataArray(ui.tab, 'dates');

    var ref = $(ui.tab).attr('href');

    var cont = $(ref);

    ResolveUrl(cont);

    // Update dates
    cont.find('.section-date').each(function (index) {
        var idxDt = index + 1;
        if (idxDt < evtDates.length)
            $(this).after(' ' + evtDates[idxDt]);
        else
            $(this).parent().remove(); // remove also parent <p>
    });

    // Prices
    var evtPrices = GetEventDataArray(ui.tab, 'prices');

    cont.find('.section-price').each(function (index) {
        if (index < evtPrices.length && evtPrices[index].length) {
            UpdateAuthField($(this), evtPrices[index]);
        }
        else {
            $(this).parent().remove();
        }
    });

    MakeExpandLink('.expandable');

    // Contacts
    var info = GetEventData(ui.tab, 'event');
    UpdateField($('.section-phone'), $('<span class="tel">').html(info.contact));

    // Video
    AppendVideo('video, audio');

    // Order form
    var titlearr = jSONtoArray(cont.find('#order-form').data('caption'));

    AppendOrderForm(cont.find('#order-form'), titlearr.length ? titlearr : [$(ui.tab).text()], $('div.prod-selected').data('prod'));
}

function GetEventDataArray(obj, field) {
    return jSONtoArray(GetEventData(obj, field));
}

function GetEventData(obj, field) {
    return $.parseJSON($(obj).data(field).replace(/'/g, '"'));
}

function OnShowTab(event, ui) 
{
    var info = GetEventData(ui.tab, 'event');
    var shop = $('#ShopDataList');

    if (info.ownercode)
    {
        var cnt = FilterShop(info.ownercode);
        
        // Reset height       
        if (cnt > 0)
        {
            shop.show();
            shop.css('height', "0"); // Fit height
        }
        else
        {
            shop.hide();
        }
    }
    else
    {
        shop.hide();
    }
}

function AppendVideo(tag) {

    $(tag).each(function () {

        var tag1 = $(this);
        var vid = tag1.attr('src');
        var w = tag1.attr('width');
        var h = tag1.attr('height');
        var isAudio = tag1.is('audio');

        var cfg = {
            provider: 'http',
            streamer: baseurl + 'streamer.ashx',
            file: isAudio ? (baseurl + vid) : vid, // patch
            image: !isAudio ? (baseurl + tag1.attr('poster')) : '',
            autostart: 'false',
            'http.startparam': 'start',
            icons: 'none',
            abouttext: 'MyWay.by',
            aboutlink: window.location.protocol + '//' + window.location.hostname
        };

        if (vid.indexOf('.flv') == -1) { // not flv video
            delete cfg.provider;
            delete cfg.streamer;
            delete cfg.image;
        }

        var v = $('<div class="videodata">');

        v.attr('rel', vid);

        var html5 = tag1.clone();

        tag1.replaceWith(v);

        v.flashembed({ src: baseurl + "player.swf",
            width: isAudio ? '320' : w,
            height: isAudio ? '24' : h,
            wmode: 'transparent',
            allowfullscreen: !isAudio,
            bgcolor: '#000000',
            w3c: false,
            onFail: function () {
                html5.attr('src', baseurl + html5.attr('src'));
                html5.attr('controls', 'controls');
                v.empty().append(html5);
            }
        }, cfg);

    });
}

function IsAuth() {
    return $('#LoginLink').length ? false : true;
}

function CommonDialogInit(name)
{
    $('.ui-dialog-titlebar').removeClass('ui-corner-all').addClass('ui-corner-top');

    $('#'+ name + ' .ui-state-default').hover(
	    function() { $(this).addClass('ui-state-hover'); }, 
	    function() { $(this).removeClass('ui-state-hover'); }
    );

    InitValidators();
}

function CommonDialogDestroy(tag)
{
    $(tag).dialog('destroy').remove();
    return $('#LoginPlace').empty();
}

function RecomendProduct(elem)
{
    var prod = $('.prod:eq(' + elem + ')');
    
    if (prod.length)
    {
        // Filter recommend
        var row = prod.parent();

        var part = $('<tr>').append(row.clone().show().removeClass('product-item'));

        part.appendTo('#Recomend');
    }
}

function SetupLogin()
{
    // Login
    $("a[href$='login']").live('click', function () {
        if (IsAuth())
            return true;

        if ($('#LoginForm').length)
            return false;

        if ($('#RegisterForm').length)
            CommonDialogDestroy("#RegDialog");

        // Load
        $.ajax({
            url: baseurl + "Login.aspx",
            data: { w: $(window).width(), h: $(this).outerHeight() },
            cache: true,
            success: function (html) {
                $("#LoginPlace").append(html.replace('Login.aspx', baseurl + "Login.aspx"));
            }
        });
        return false;
    });
    
    // Register
    $("a[href$='register']").live('click', function () {
        if (IsAuth())
            return false;
        
        if ($('#RegisterForm').length)
            return false;
            
        if ($('#LoginForm').length)
            CommonDialogDestroy("#LoginDialog");
    
        // Load
        $.ajax({
          url: baseurl + "Register.aspx",
          data: {w : $(window).width(), h : $(this).outerHeight()},
          cache: true,
          success: function(html){
            $("#LoginPlace").append(html);
          }
        });

        return false;
    });


    // ChangePass
    $("a[href$='changepass']").click(function () {
        if (!IsAuth())
            return false;

        if ($('#ChangeForm').length)
            return false;

        if ($('#LoginPlace > *').length)
            CommonDialogDestroy("#LoginDialog, #RegisterDialog");

        // Load
        $.ajax({
            url: baseurl + "ChangePass.aspx",
            data: { w: $(window).width(), h: $(this).outerHeight() },
            cache: true,
            success: function (html) {
                $("#LoginPlace").append(html);
            }
        });

        return false;
    });
}

function SetupLayout(obj)
{
    if ($(obj).hasClass("hide-advert"))
    {
        var adv = $('#Advert');
        adv.data('visible', adv.parent().is(':visible'));
        adv.parent().hide();
    }

    if ($(obj).hasClass("hide-shop"))
    {
        var shop = $('#ShopDataList');
        shop.data('visible', shop.is(':visible'));
        shop.hide();
    }

    if ($(obj).hasClass("product-link")) {
        $('#ShopDataList, #Advert, #Recomend').find('.ui-state-active, .prod-selected').removeClass('ui-state-active prod-selected');

        $(obj).parent().addClass('prod-selected');

        $(obj).closest('table[id$="Advert"], table[id$="Recomend"]').find('td:first').addClass('ui-state-active');
    }
}

function ResolveUrl(obj) {
    obj.find('img:not([src^="http"])').each(function () {
        $(this).attr('src', baseurl + $(this).attr('src'));
    });
}

function InitValidators() {
    $('.invalid-input').live('focus', function () {
        $(this).removeClass('invalid-input').removeAttr('title');
    });
}

function InitValidators2(group) {
    var originalValidationFunction = Page_ClientValidate;
    if (originalValidationFunction && typeof (originalValidationFunction) == "function") {
        Page_ClientValidate = function (group) {
            originalValidationFunction(group);

            if (!Page_IsValid) {
                // your code here
                for (i = 0; i < Page_Validators.length; i++) {
                    if (Page_Validators[i].validationGroup == group && !Page_Validators[i].isvalid) {
                        var ctrl = $('#' + Page_Validators[i].controltovalidate);

                        if (!ctrl.hasClass('invalid-input')) {
                            ctrl.addClass('invalid-input');
                            ctrl.attr('title', Page_Validators[i].title);
                        }
                    }
                }
            }
        };
    }
}

function InitForm() {
    $('#send_contact').live('click', function () {
        $('#OrderForm').submit();
        return false;
    });

    InitValidators();

    // Hover states on the static widgets
    $('#send_contact').hover(
        function () { $(this).addClass('ui-state-hover'); },
        function () { $(this).removeClass('ui-state-hover'); }
    );

    $('#OrderForm').ajaxForm({
        beforeSubmit: function (formData, jqForm, options) {
            var form = jqForm[0];

            if (!form.form_name.value) {
                $('#form_name').addClass('invalid-input');
            }

            if (!form.form_phone.value || !(form.form_phone.value && testNumber(form.form_phone.value))) {
                $('#form_phone').addClass('invalid-input');
            }

            if (form.form_email.value && !testMail(form.form_email.value)) {
                $('#form_email').addClass('invalid-input');
            }

            var valid = $('#OrderForm .invalid-input').length ? false : true

            if (valid) {
                $('#OrderForm fieldset > *').hide();
                $('#OrderForm fieldset').append(GetLoader());
            }

            return valid;
        },
        success: function (responseText, statusText) {
            if (statusText == 'success') {
                $("#OrderForm fieldset").empty().append(responseText);
            }
        }
    });
}

function testMail(mail) {
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9])+$/;
    //    var filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
    return filter.test(mail);
}

function testNumber(num) {
    //    var filter = /^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/;
    //    return filter.test(num);
    // Temporary
    return num.length;
}

function SetupProduct(data, meta) {
    $(data).each(function () {
        $('<option>' + this.toString() + '</option>').appendTo('#form_product');
    });

    if (meta) {
        $('#form_price').val(meta.price);
    }

    if (data.length == 1) {
        $('#form_product').parent().hide();
    }
}

function GetLoader() {
    return $('<div class="loader">').html('<img src="' + baseurl + 'images/ajax-loader.gif"/>');
}
