function Mask(){
    $(".price").each(function(){
        var current = 0;
        var text = $(this).text();
        var newtext = '';
        var length = $(this).text().length;
        for(i=length-1; i>=0; i--){
            current++;
            newtext=text.charAt(i) + newtext;
            //                alert(text.charAt(i))
            if(current == 3){
                current=0;
                if(text.charAt(i-2)!=' ' & text.charAt(i-1)!=' '){
                    newtext=' '+newtext;
                }
            }
        }
        $(this).text(newtext)
    })
}

function VikupLoad(){
    $("#VikupAvto").remove();
    $("#content").load("scripts/guest/vikup.php", function(){
        var vikup=$("#VikupAvto");
        $('input:text').setMask();
        vikup.dialog({
            bgiframe: true,
            autoOpen: true,
            height: 450,
            minWidth: 300,
            draggable:false,
            modal: true,
            buttons: {
                'Отправить заявку': function() {
                    $('form').submit();
                    alert("Спасибо! Ваша заявка принята");
                },
                'Отмена': function() {
                    $(this).dialog('close');
                //                    document.location.href = "#/main/";
                }
            },
            close: function(){
                $("#VikupAvto").remove();
                document.location.href = "#/main/";
            }
        })
    })
}

function MaskMin(){
    $(".pricemin").each(function(){
        var current = 0;
        var text = $(this).text();
        var newtext = '';
        var length = $(this).text().length;
        for(i=length-1; i>=0; i--){
            current++;
            newtext=text.charAt(i) + newtext;
            //                alert(text.charAt(i))
            if(current == 3){
                current=0;
                if(text.charAt(i-2)!=' ' & text.charAt(i-1)!=' '){
                    newtext=' '+newtext;
                }
            }
        }
        $(this).text(newtext)
    })
}
function ContactsLoad(){
    $.post("scripts/guest/contacts/contacts.php",function(data){
        $("#content").replaceWith(data);
    })
}

//function LoadFooter(){
//    $.post("scripts/guest/footer.php",function(data){
//       $("#footer").replaceWith(data);
//    })
//}

function GuestgetNews(){
    //    var date = year + "." + month + "." + day;
    $.post("scripts/guest/news/news.php",function(data){
        $("#sidebar").replaceWith(data);
    });
}

var ua = navigator.userAgent.toLowerCase();
var isOpera = (ua.indexOf('opera')  > -1);
var isIE = (!isOpera && ua.indexOf('msie') > -1);

function getDocumentHeight() {
    return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, getViewportHeight());
}

function getViewportHeight() {
    return ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
}

function screenSize() {
    var w, h; // Объявляем переменные, w - длина, h - высота
    w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
    h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
    return {
        w:w,
        h:h
    };
}

function scrollToTop(){
    window.scrollTo(0,0);
}

function MainLoad(){
    $.post("scripts/guest/cars/carsRandom.php",function(data){
        //        DropDownMenus()
        $("#content").replaceWith(data);
        $('#slider1').s3Slider({
            timeOut: 6000
        });
        if (!$.browser.msie){
            Mask();
        }
        $("button[rel]").overlay(function() {
            var showing = this.getContent().find("div.showing");
            showing.load(this.getTrigger().attr("href"),function(){
                $(this).scrollTop(0);
                if (!$.browser.msie){
                    Mask();
                }                
            })
        });
    });
}

function URL_Analyzator(){

    var URL = document.location.hash;
    URL = URL.split("/");
    scrollToTop();
    $("img[src*='transparent.png']:hidden").remove();
    $(".close").remove();
    switch (URL[1]) {
        case "cars":
            switch (URL[2]){
                case "nov":
                    document.title='Альянс Авто | Новые Автомобили';
                    CarsLoad(URL[3],URL[4],URL[5],1,0);
                    //                    LoadFooter();
                    break;

                //                case "usa":
                //                    document.title='Альянс Авто | Автомобили из США';
                //                    CarsLoad(URL[3],URL[4],URL[5],2,1);
                ////                    LoadFooter();
                //                    break;

                case "old":
                    document.title='Альянс Авто | Автомобили с Пробегом';
                    CarsLoad(URL[3],URL[4],URL[5],0,0);
                    //                    LoadFooter();
                    break;
            }
            break;

        case "newscars":
            document.title='Альянс Авто | Новости';
            CarsNews(URL[2]);
            //            LoadFooter();
            break;

        case "service":
            document.title='Альянс Авто | Услуги';
            ServiceLoad(URL[2]);
            //            LoadFooter();
            break;

        case "search":
            document.title='Альянс Авто | Поиск';
            SearchLoad();
            //            LoadFooter();
            break;

        case "contacts":
            document.title='Альянс Авто | Контакты';
            ContactsLoad();
            //            LoadFooter();
            break;
            
        case "main":
            document.title='Альянс Авто | Главная';
            MainLoad();
            //            LoadFooter();
            //$("#content").repalceWith("<div id=content><h2>Добро пожаловать в панель упраления автосалоном</h2><p>Выберите интересующее вас дейсвие.</p></div>");
            break;

        case "vikup":
            document.title='Альянс Авто | Заявка на выкуп автомобиля';
            VikupLoad();
            break;

        case "admin":
            switch (URL[2]){
                case "car":{
                    document.title='Альянс Авто | Админка | Упраление Автомобилями';
                    CarLoad();
                    //                        LoadFooter();
                    break;
                }
                case "login":{
                    document.title='Альянс Авто | Вход в Админку';
                    AdminLogin();
                    //                        LoadFooter();
                    break;
                }
                case "mark":{
                    document.title='Альянс Авто | Админка | Упраление Производителями';
                    MarkLoad();
                    //                        LoadFooter();
                    break;
                }
                case "model":{
                    document.title='Альянс Авто | Админка | Упраление Моделями';
                    ModelLoad();
                    //                        LoadFooter();
                    break;
                }
                case "color":{
                    document.title='Альянс Авто | Админка | Упраление Цветами';
                    ColorLoad();
                    //                        LoadFooter();
                    break;
                }
                case "engine":{
                    document.title='Альянс Авто | Админка | Упраление Двигателями';
                    EngineLoad();
                    //                        LoadFooter();
                    break;
                }
                case "bodytype":{
                    document.title='Альянс Авто | Админка | Упраление Типами Корпуса';
                    BodyTypeLoad();
                    //                        LoadFooter();
                    break;
                }
                case "service":{
                    document.title='Альянс Авто | Админка | Упраление Услугами';
                    ServiceLoad();
                    //                        LoadFooter();
                    break;
                }
                case "mainpage":{
                    document.title='Альянс Авто | Админка | Упраление Главной Страницей';
                    MainPageLoad();
                    break;
                }
                case "news":{
                    document.title='Альянс Авто | Админка | Упраление Новостями';
                    NewsLoad();
                    //                        LoadFooter();
                    break;
                }
            }
            break;

        default:
            //alert(re);
            break;
    //        var last = $("img[src*='transparent.png']:hidden:last");
        
    //        $("body").append(last);
    }    
//            tool = $.getScript("javascripts/tooltip.js");
//    LoadFooter();
} 
function PromptMe() {
    // some application vars
    // the sole public method to manipulate this application
    this.NewVal = function(currentState) {
        var NewVal = currentState
        unFocus.History.addHistory(NewVal);
    }
    this.historyListener = function(historyHash) {
        // update the stateVar
        stateVar = historyHash;
        URL_Analyzator();
    }
    unFocus.History.addEventListener('historyChange', this.historyListener);
    this.historyListener(unFocus.History.getCurrent());
    var historyVar;
}

function hashURL(section,url){
    document.location.hash = "/"+section+"/"+url;
    //alert(document.location.hash.replace("#/",""));
    URL_Analyzator();
}
$(".ajax").click(function(){
    URL_Analyzator();
    historyVar.NewVal(document.location.hash);    
})
$(document).ready(function(){
    $("#content").css("min-height", getDocumentHeight());
    if(document.location.hash == ""){
        document.location.hash = "/main/";
    }
    GuestgetNews();
    URL_Analyzator();    
    historyVar = new PromptMe();
    $("#loading").ajaxStart(function(){
        //        tool = null;
        $("<div id='over'></div>").appendTo(document.body).addClass("ui-widget-overlay").css({
            width:screenSize().w,
            height:getDocumentHeight(),
			"z-index":9999
            })
        $(this).css("width",screenSize().w);
        $(this).css("height",screenSize().h);
        $(this).fadeIn();
    //        var last = $("img[src*='transparent.png']:hidden:last");
    //        $("img[src*='transparent.png']:hidden").remove();
    //        $("body").append(last);
    })    
    $("#loading").ajaxStop(function(){        
        var URL = document.location.hash;
        URL = URL.split("/");
        $("#over").remove();        
        $(this).fadeOut("slow");
        if (URL[1] != 'admin'){
            vtip();            
            $("a[rel='lightbox']").lightBox();
        }
    })  
//    $(document).ajaxSuccess(function(){
////        window.setTimeout(function(){
//            $(this).load(function(){
//                if($.browser.msie){addIECorners(); }else {addCorners();}
//            })
////        }, 8000)
//    })

})


