$(document).ready(function() {
// config
    var ar = 'ar'; //ajax receiver's address
    $.ajaxSetup({
        url: ar,
        type: "POST"
    });
//--

    $('#siteMenu').siteMenu();
    $('#subscribe').subscriber();

// Tabs functionality
    var sblock = $('#search');
    $('DL.tab', sblock).dltabs();
    
    $('SELECT', sblock)
        .live('keypress', function() { $(this).trigger('change'); })
        .live('change', function() { asearch(); });
    
    $("INPUT[name='used[search]']", sblock).live('click', function() {
        var url = window.document.location.href;
        var page = xslice(url.substr(7), '/');
        if (page == 'search') {
            $('SELECT:first', sblock).trigger('change');                                    
        } else {
            $.cookie('search_form', get_search_prm(true));
            var lim = url.indexOf('/'+page);
            var search_page = url.slice(0, lim)+'/search';
            //alert(search_page);
            window.document.location.href = search_page;
        }        
    });
    //Create searching data
    var get_search_prm = function(json) {
        var json = json || false;
        var url = window.document.location.href;
        var page = xslice(url.substr(7), '/');
        //var min_price = $('#find_used .min_price INPUT').val();
        //var max_price = $('#find_used .max_price INPUT').val();
        var min_price = $('#find_used #min_price').val();
        var max_price = $('#find_used #max_price').val();
        if (json) {
            var prm = '{';
            prm += '"action":"asearch","type":"used","used":{';
            $('#find_used SELECT').each(function(i) {
                //var name = $(this).attr('name');
                var name = this.className;
                var value = $(this).val();
                prm += (i>0?',':'')+'"'+name+'":"'+value+'"';
            });
            prm += '},"page":"'+page+'"' //,"min_price":"'+min_price+'","max_price":"'+max_price+'"';
            return prm+'}';
        } else {
            var prm = 'action=asearch&type=used';
            $('#find_used SELECT').each(function() {
                var name = $(this).attr('name');
                var value = $(this).val();
                prm += '&'+name+'='+value;
            });
            prm += '&page='+page; //+'&min_price='+min_price+'&max_price='+max_price;
            return prm;
        }
    }
    
    var asearch = function() {
        prm = get_search_prm();
        $('.tab_content .total', sblock).addClass('loading');
        $.ajax({ 
            data: prm,
            dataType: 'json',
            success: function(json) {
                xlog(json);
                if (json['html']) {
                    $('#search_res').hide().html(json['html']).fadeIn('slow');
                } else {
                    $('.options', sblock).text("Click on 'Search' to see the full result")
                    .not('.open').siblings('.submit').find('A').trigger('click');
                }
                $('.tab_content .total INPUT', sblock).new_val(json['n']);
                $('.tab_content .total', sblock).removeClass('loading');
            }
        });    
        
    }
    
    // More Options func
    $('.tab_content .submit A', sblock).live('click', function(i) {
        atab = $(this).parent().parent().attr('tab');
        $('.tab_content[tab='+atab+'] .options', sblock).toggleClass('open').fadeToggle("slow", "linear");
        return false;        
    });
//--

// Gallery functionality
    var gblock = $('#collage') //Gallery Block;
    gblock.scrollGallery();
    $('.list .item:first .image A', gblock).trigger('click');
    if ($('.preview .list .item', gblock).length > 1) setInterval("nextImage()", 5000);
//--
 
    
// Site fitches    
    //Banners click href
    $('#banners DL, #offers DL.banner').each(function() {
        if ($('DD.text', this))
        var atext = $('DD.text', this).text();
        //var atext = $('DT', this).text();
        $(this).attr('title', atext);        
        $(this).click(function() {
            var alink = $('DD.link A', this).attr('href');
            document.location.href = alink;
        });
    });
    
    //fix: siteMenu position [Opera]
    if ($.browser.opera){ $('#siteMenu UL').width($('#siteMenu LI').length*120+5); }
//--

    $("#carInfo .item LI A").live('click', function() {
        $(this).lightBox().trigger('click');
        return false;    
    }); 
    
    $('#car_sale .image A').live('click', function() {
        var href = $(this).attr('href');
        var car_id = xslice(href, '#');
        CarInfo(car_id);
    });


});

function CarInfo(id) {
     $('#carInfo').slideUp('fast').load('ar', {action:'car_info', id:id}, function(){ $(this).fadeIn('slow'); });
}

function nextImage() { $('#collage .arr.next').trigger('click'); } 

function xslice(s, sep) {
    while (s.substring(0,1) != sep) s = s.substring(1, s.length);
    return s.substring(1, s.length);
}


jQuery.fn.new_val = function(value){
    var old_val = $(this).val();
    $(this).css('opacity','0').val(value).animate({opacity:1}, 350);
}

jQuery.fn.dltabs = function(atab){
    //if (typeof atab == 'undefined') atab = 1; //active tab
    var atab = atab || 1;
    var shell = $(this).parent(); //container with tabs
    $('H3', shell).each(function(i) {
        if (i == 0) {
            exc = $(this);
            exc.addClass('exc1');                
        }
        else $(this).remove();
    });
    var exc1 = exc;
    var tabs = $('.tab', shell).get(); //getting all tabs in array
    var che = tabs[0]; //active element
    //var tabtag = tabs[0].tagName; //tag of tab
    var atab_content = $(".tab:eq("+(atab-1)+") > DD", shell); //active tab's content
    var xtabs = []; //tabs array
    xtabs[0] = []; 
    xtabs[0]['active'] = atab; //number of active tab
    xtabs[0]['total'] = 0; //quantity of tabs
    
    $.each(tabs, function(i, tab) { 
        var n = i + 1; //number of tab
        var ntab = []; //tab element [new tab]
        ntab['status'] = '';
        $(tabs[i]).attr('tab', n).addClass('x_tab');
        ntab['tab'] = $(tabs[i]);
        $('DT', tabs[i]).attr('tab', n).addClass('tab_menu');
        ntab['menu'] = $('DT', tabs[i]);
        $('DD', tabs[i]).attr('tab', n).addClass('tab_content');        
        ntab['content'] = $('DD', tabs[i]);
        xtabs[n] = ntab;
        xtabs[0]['total']++; //increasing the quantity of tabs
    });
    $(xtabs[xtabs[0]['total']]['menu']).addClass('last'); //add Class "last" for last tab-menu
    $(xtabs[1]['menu']).addClass('first'); //add Class "first" for last tab-menu
    
    var process_tab = function(atab) {
        $('>.tab_content', shell).remove();
        for (n = 1; n <= xtabs[0]['total']; n++) {
            if (n == atab) {
                $(xtabs[n]['menu']).addClass('active');
                atab_content = xtabs[n]['content']; //active-tab's content
            } else $(xtabs[n]['menu']).removeClass('active');
            shell.append($(xtabs[n]['menu']));
        }
        shell.append(exc1);
        atab_content.hide().appendTo(shell).fadeIn('slow');
    };
    
    $('.tab_menu', shell).css('cursor', 'pointer').click(function() {
        var atab = $(this).attr('tab');
        process_tab(atab);
    });
    
    process_tab(atab);
}


jQuery.fn.siteMenu = function(){
    var SMpar = $(this); //Top Menu
    var SM = $('>UL', SMpar); //Sub menu
    
    if ($('BODY').attr('id') == 'index') var wSMsub = $('#middle .right').width();
    else var wSMsub = $('#center .middle').width();

    var xR = 13;
    if ($.browser.mozilla) xR = 10;
    if ($.browser.msie) {
        if ($.browser.version == '7.0') xR = -1;
        else xR = 9;
    }
    
    $('> UL > LI.active > UL', SMpar).clone().css({ zIndex:390, right:xR }).width(wSMsub).appendTo('#center').addClass('subMenu2');
    
    $('>LI', SM).each(function(e) { //var n = e+1;
        var SMsubpar = $(this);     //SMsubpar.attr('n', n);
        var SMsub = $('>UL', this); //SMsub.attr('par', n)        
        var subPlace = $('#center');
        if (SMsub.length == 1) {
            SMsubpar.mouseenter(function(){ 
                SMsub.appendTo(subPlace).addClass('subMenu').css({ right:xR }).width(wSMsub).fadeIn(188);
            });
            SMsub.mouseleave(function(){
                SMsub.appendTo(SMsubpar).width(wSMsub).fadeOut(288);
            });
        } else SMsubpar.mouseenter(function(){ 
            $('>UL.subMenu', subPlace).appendTo(SMsubpar).width(wSMsub).fadeOut(288);
        });
    });
}

jQuery.fn.scrollGallery = function(RotationSpeed){
    var g = $(this); //gallery block
    var pList = $('.preview .list', g); //Preview images List
    var i = []; //previw box images
    i[0] = []; //information about gallery
    i[0]['width'] = pList.width(); //width of preview images list
    var next = $('.arr.next', this); //previous image button
    var prev = $('.arr.prev', this); //next image button
    
    //Collect all images in i
    $('.preview .item', g).each(function(n) {
        var no = n+1; //Number of image (for that the first one item will have number - 1, and not - 0 ☺)
        var img = []; //image item
        if ($(this).hasClass('active')) i[0]['active'] = no; 
        img['res'] = $(this);
        img['thumb'] = $('DD.image IMG', this).attr('src');
        img['width'] = $(this).width() + parseInt($(this).css('marginRight'));
        img['fullsize'] = $('DD.image A', this).attr('href');
        $([img['fullsize']]).preload();  
        img['title'] = $('DT', this).text();
        img['text'] = $('DD.text', this).html();
        $(this).attr('img', no);
        i[no] = img; //add item into the list
        i[0]['total'] = no;
        i[0]['width'] = i[0]['width']-img['width'];
    }).click(function(){ activeImage($(this).attr('img')); return false; });

    next.click(function(){ activeImage(i[0]['active'] + 1); return false; });
    prev.click(function(){ activeImage(i[0]['active'] - 1); return false; });
    
    var activeImage = function(no) {
        var no = (no>i[0]['total']?1:(no<=0?i[0]['total']:no));
        i[0]['was_active'] = i[0]['active'];
        i[0]['active'] = no;
        
        $('LI.item', g).removeClass('active');
        i[no]['res'].addClass('active');
        $('.src IMG', g).attr('delete', 'yes');
        $('DL.description', g).attr('delete', 'yes');
        
        $('.description', g).fadeOut(400);
        if ( (i[no]['title'] != '')||(i[no]['text'] != ''))        
            $('<dl class="description">'
                +(i[no]['title'] != ''?'<dt>'+i[no]['title']+'</dt>':'')
                +(i[no]['text'] != ''?'<dd>'+i[no]['text']+'</dd>':'')
                +'<div class="bg"></div>'
            +'</dl>')
                .css({ display:'none', position:'absolute', left:30, top:15, zIndex:90 })
                .prependTo(g)
                .fadeIn(650, function(){
                    $(this).attr('delete', 'not');
                    $('DL.description[delete!="not"]', g).each(function() {
                        $(this).fadeOut(150, function() { $(this).remove(); });    
                    });
                });
        
        $('<img />')
            .attr('src',i[no]['fullsize']).attr('alt',i[no]['title'])
            .css({ display:'none', position:'absolute', left:0, top:0 })
            .appendTo($('.src', g))
            .fadeIn(650, function(){
                $(this).attr('delete', 'not');
                $('.src IMG[delete!="not"]', g).each(function() {
                    $(this).fadeOut(150, function() { $(this).remove(); });    
                });
            });
    }
    
    prev.mouseenter(function() {
        list.ul.animate({ left:'1000px'}, 10000);
    }).mouseleave(function() {
        list.ul.stop(true, false);
    });
    
    next.mouseenter(function() {
        list.ul.animate({ left:'-1000px'}, 10000);
    }).mouseleave(function() {
        list.ul.stop(true, false);
    });
}

$.fn.subscriber = function(){
    if ((typeof(this) != 'undefined')&&(this.length == 1)) {
        var form = $('FORM', this); // Newsletter form
        var body = $('DD', this); // Newsletter body
        var submit = $('.submit', this); // Newsletter Submit block
        var iSubmit = $('INPUT', submit); // Newsletter Submit field
        var ar = 'ar'; // ar ~ Ajax Receiver page
        var ar_act = 'newsletter'; // ar_act ~ Ajax Receiver's action name
        var anewID = 'new_newsletter'; // ID for link that making anew newsletter
        var fnName = 'yourname'; // fn ~ Field Name
        var fnMail = 'youremail'; // fn ~ Field Name
        
        var lMail = $('LABEL[for='+fnMail+']', this); // l ~ Label
        var iMail = $('#'+fnMail, this); // i ~ Input
        var tMail = lMail.text(); // t ~ title/text
        lMail.hide();
        iMail.val(tMail)
            .live('focusin', function(){ if ($(this).val() == tMail){ $(this).val(''); }})
            .live('focusout', function(){ if ($(this).val() == ''){ $(this).val(tMail); }});
        
        var ar_opt = { //ajax receiver options 
            target:     form.attr('id'),
            url:        ar,
            type:       'post',
            dataType:   'json',
            data:       { action:ar_act },
            beforeSubmit: function(formData, jqForm, options) {
                var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!filter.test(iMail.val())) {
                    alert('Please, Enter the valid e-mail address.');
                    iMail.focus();
                    return false;
                }
                submit.addClass('loading');
                return true; 
            },
            success: function(json, statusText, xhr, $form) { 
                xlog(json);
                if (json['status']) var tpl = '<b>{text}</b><p>{post}</p><a href="#anew" id="'+anewID+'" title="Subscribe another email">Back to the form</a>';
                else var tpl = '<b>Error</b><p>Something is wrong</p><a href="#anew" id="new_newsletter" title="Subscribe another email">Back to the form</a>';
                var res = tpl.supplant(json);
                body.hide().html(res).fadeIn('slow');
                submit.removeClass('loading');
            }
        }
        
        iSubmit.live('click', function(){ 
            form.ajaxSubmit(ar_opt);
            return false;
        });
        
        var anew = form.clone();
        $('#'+anewID, this).live('click', function() {
            body.hide().html(anew).fadeIn('slow');
            return false;        
        });
        
    }
}


function xlog(data) { try { console.log(data); } catch(e){ /*alert(e);*/ } }

$.fn.preload = function() { this.each(function() { $('<img/>')[0].src = this; }); }
