var fiatThemeCookie = readCookie('fiattheme');
var fontSize = {'normalfont':'100%', 'bigfont':'140%'};
var theme = {'std_yellow':'std_yellow', 'big_yellow':'big_yellow','big_white':'big_white','std_white':'std_white','textonly':'text_only'};
var dealerCity = "";
var dealerZip = "";


jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}
function setEventsHandlers(){
    $("a[title='Newsletter']").click(function(){
        createPopupWindow();
    });
}

function showAccessKeys() {
    if($('#popupkeymenu').css('height')=='auto'){
        $('#popupkeymenu').css('visibility','hidden');
        $('#popupkeymenu').css('height', '0');
    }
    else{
        $('#popupkeymenu').css('visibility','visible');
        $('#popupkeymenu').css('height', 'auto');
        $('#popupkeymenuDivClose').click(function () { showAccessKeys(); });
    }
};
function createPopupWindow(html, width, height){
    //Get the screen height and width  
    var maskHeight = $(document).height();  
    var maskWidth = $(window).width();
    //Set height and width to mask to fill up the whole screen   
    $(document.body).append('<div id="popupBackground"></div><div id="popupContent"><div class="popupDiv"><div id="popupDivClose"></div><div id="popupDivText"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div></div></div>');
    $('#popupBackground').css({'width':maskWidth,'height':maskHeight,'position':'absolute'});
    //Get the window height and width  
    /*var winH = $(window).height();  
    var winW = $(window).width();                   
    //Set the popup window to center  
    $('.popupDiv').css({'margin':'0px','position':'absolute'});
    $('.popupDiv').css('top',  winH/2-$('.popupDiv').height()/2);  
    $('.popupDiv').css('left', winW/2-$('.popupDiv').width()/2);*/  
    $('#popupDivClose').click(function(){closePopupWindow();});
    $.ajax({
            type: "GET",
            url: "/Newsletter/Create",
            async: true,
            success: function(htmla){
                $('#popupDivText').html(htmla);
                $('#popupDivText #abbrechen').click(function(){closePopupWindow();});
                $('#popupDivText .newsletter form').submit(function(fn) {
                    fn.preventDefault();
                    postNewsletter();
                    return false;
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#popupDivText').html(textStatus);
            }
    });
}
function postNewsletter() {
        $.ajax({
            type: "POST",
            url: "/newsletter/create",
            async: true,
            //data: "subject=" + $('#popupDivText .newsletter form #Subject').val() + "&Email=" + $('#popupDivText .newsletter form #Email').val() + "&FirstName=" + $('#popupDivText .newsletter form #FirstName').val() + "&Lastname=" +$('#popupDivText .newsletter form #Lastname').val() + "&submit=Absenden",
            data: $('#popupDivText .newsletter form').serialize(),
            success: function(html){
                $('#popupDivText').html(html);
                $('#popupDivText #abbrechen').click(function(){closePopupWindow();});
                $('#popupDivText .newsletter form').submit(function(fn) {
                    fn.preventDefault();
                    postNewsletter();
                    return false;
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#popupDivText').html(textStatus);
            }
        });
}
function createMagazinWindow(html, width, height) {
	trackingPixelPreislisteConfirmation();
    //Get the screen height and width  
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
    //Set height and width to mask to fill up the whole screen   
    $(document.body).append('<div id="popupBackground"></div><div id="popupContent"><div class="popupDiv"><div id="popupDivClose"></div><div id="popupDivText"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div></div></div>');
    $('#popupBackground').css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute' });
    //Get the window height and width  
    /*var winH = $(window).height();  
    var winW = $(window).width();                   
    //Set the popup window to center  
    $('.popupDiv').css({'margin':'0px','position':'absolute'});
    $('.popupDiv').css('top',  winH/2-$('.popupDiv').height()/2);  
    $('.popupDiv').css('left', winW/2-$('.popupDiv').width()/2);*/
    $('#popupDivClose').click(function () { closePopupWindow(); });
    $.ajax({
        type: "GET",
        url: "/AutonomyMagazin/Create",
        async: true,
        success: function (htmla) {
            $('#popupDivText').html(htmla);
            $('#popupDivText #abbrechen').click(function () { closePopupWindow(); });
            $('#popupDivText .newsletter form').submit(function (fn) {
                fn.preventDefault();
                postMagazin();
                return false;
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#popupDivText').html(textStatus);
        }
    });
}
function postMagazin() {
    $.ajax({
        type: "POST",
        url: "/AutonomyMagazin/create",
        async: true,
        //data: "subject=" + $('#popupDivText .newsletter form #Subject').val() + "&Email=" + $('#popupDivText .newsletter form #Email').val() + "&FirstName=" + $('#popupDivText .newsletter form #FirstName').val() + "&Lastname=" +$('#popupDivText .newsletter form #Lastname').val() + "&submit=Absenden",
        data: $('#popupDivText .newsletter form').serialize(),
        success: function (html) {
            $('#popupDivText').html(html);
            $('#popupDivText #abbrechen').click(function () { closePopupWindow(); });
            $('#popupDivText .newsletter form').submit(function (fn) {
                fn.preventDefault();
                postMagazin();
                return false;
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#popupDivText').html(textStatus);
        }
    });
}
function createProspektePopup(thisProspekte,html, width, height) {
	trackingPixelPreislisteConfirmation();
    var selectedModelClass = $(thisProspekte).attr("class");
    if (fiatThemeCookie == 'textonly') {
        $.ajax({
            type: "GET",
            url: "/CatalogOrder/create",
            async: true,
            success: function (htmla) {
                $('.Prospektepopup_textversion').remove();
                $(thisProspekte).after('<div class="Prospektepopup_textversion">' + htmla + '</div>');
                $('.Prospektepopup_textversion .prospect_popup form').submit(function (fn) {
                    fn.preventDefault();
                    postProspect();
                    return false;
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#popupDivText').html(testStatus);
            }
        });
    }
    else {
        //Set height and width to mask to fill up the whole screen   
        $(document.body).append('<div id="popupBackground"></div><div id="popupContent"><div class="popupDiv"><div id="popupDivClose"></div><div id="popupDivText"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div></div></div>');
        $('#popupDivClose').click(function () { closePopupWindow(); });
        $.ajax({
            type: "GET",
            url: "/CatalogOrder/create",
            async: true,
            success: function (htmla) {
                $('#popupDivText').html(htmla);
                $('#popupDivText #abbrechen').click(function () { closePopupWindow(); });
                var maskHeight = $(document).height();
                var maskWidth = $(window).width();
                $('#popupBackground').css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute' });
                var modelCheckboxes = $('div.prospekt-row input:checkbox');
                for (var i = 0; i < modelCheckboxes.length; i++) {
                    if ($(modelCheckboxes[i]).hasClass(selectedModelClass))
                        $(modelCheckboxes[i]).attr('checked', true);
                }

                $('#popupDivText .prospect_popup form').submit(function (fn) {
                    if (atLeastOneProspektSelected()) $('#hiddenField').val('Checked');
                    else $('#hiddenField').val('NOT Checked');
                    fn.preventDefault();
                    postProspect();
                    return false;
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#popupDivText').html(textStatus);
            }
        });
        $('#popupContent').center();
        //Get the screen height and width  
    }
}
function postProspect() {
    $.ajax({
        type: "POST",
        url: "/CatalogOrder/create",
        async: true,
        data: $('#popupDivText .prospect_popup form').serialize(),
        success: function (html) {            
            $('#popupDivText').html(html);
            $('#popupDivText #abbrechen').click(function () { closePopupWindow(); });
            $('#popupDivText .prospect_popup form').submit(function (fn) {
                if (atLeastOneProspektSelected()) $('#hiddenField').val('Checked');
                else $('#hiddenField').val('NOT Checked');           
                fn.preventDefault();
                postProspect();
                return false;
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $('#popupDivText').html(textStatus);
        }
    });
}

function atLeastOneProspektSelected(){
     var selectedBrochures = $('#Prospekt1').attr('checked') || $('#Prospekt2').attr('checked') || $('#Prospekt3').attr('checked') || $('#Prospekt4').attr('checked') || $('#Prospekt5').attr('checked')
                            || $('#Prospekt6').attr('checked') || $('#Prospekt7').attr('checked') || $('#Prospekt8').attr('checked') || $('#Prospekt9').attr('checked')
                            || $('#Prospekt10').attr('checked') || $('#Prospekt11').attr('checked');
     return selectedBrochures;
}

function createElementPopup(thisElement, name) {
    if (fiatThemeCookie == 'textonly') {
        $.ajax({
            type: "GET",
            url: "/fahrhilfen-modelle/element/" + name + "/true",
            async: true,
            success: function (htmla) {
                $('.elementpopup_textversion').remove();
                $(thisElement).after('<div class="elementpopup_textversion"><div class="eletext">' + htmla + '</div></div>');
                
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#popupDivText').html(testStatus);
            }
        });

    }
    else {
        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        $(document.body).append('<div id="popupBackground"></div><div id="popupContent"><div class="popupDiv"><div id="popupDivClose"></div><div id="popupDivText"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div></div></div>');
        $('#popupBackground').css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute' });
        $('#popupDivClose').click(function () { closePopupWindow(); });
        $.ajax({
            type: "GET",
            url: "/fahrhilfen-modelle/element/" + name + "/true",
            async: true,
            success: function (htmla) {
                $('#popupDivText').html(htmla);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $('#popupDivText').html(testStatus);
            }
        });
        $('#popupContent').center();
    }
}
function closePopupWindow(){
    $('#popupBackground').remove();
    $('#popupContent').remove();
}

function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("search_map_canvas"),
        myOptions);
}

function initializeLocation() {
    if ( $('#centerdetail_map').length ) {
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var myOptions = {
          zoom: 8,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("centerdetail_map"),
            myOptions);
    }
}
  
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}
function setTextOnly() {
    fullName = 'textonly';
    $('link[@rel*=style][title]').each(function(i) {
        this.disabled = true;
        if (this.getAttribute('title') == theme[fullName]) this.disabled = false;
    });
    createCookie('fiattheme',fullName,365);
}

function setTheme(name){
    var fiatFontSizeCookie = readCookie('fiatfontsize');
    if(!fiatFontSizeCookie){
        createCookie('fiatfontsize','std',365);
        fiatFontSizeCookie = 'std';
    }
    fullName = fiatFontSizeCookie + '_' + name;
    $('link[@rel*=style][title]').each(function(i) {
        this.disabled = true;
        if (this.getAttribute('title') == 'index' || this.getAttribute('title') == theme[fullName]) this.disabled = false;
    });
    createCookie('fiattheme',name,365);
}

function setFontSize(name){
    var fiatThemeCookie = readCookie('fiattheme');
    if(!fiatThemeCookie){
        createCookie('fiattheme','white',365);
        fiatThemeCookie = 'white';
    }
    fullName = name + '_' + fiatThemeCookie;
    $('link[@rel*=style][title]').each(function(i) {
        this.disabled = true;
        if (this.getAttribute('title') == 'index' || this.getAttribute('title') == theme[fullName]) this.disabled = false;
    });
    createCookie('fiatfontsize',name,365);
}

function isUndefinedOrNull(variable){
    if(typeof variable === 'undefined')
        return true;
    return false;
}

function backToDealers(codeD, rangeD) {
    var regCode = new RegExp(/^([0-9]){5}$/);
    var city = "";
    var code = "";
    var coder = codeD + ""; 
    if (coder.match(regCode)) { code = codeD; }
    else { city = codeD; }
    if (coder != "") {
        //$("#code").val(coder);
       // if ($("#code").val() == "")
         //   $('#code').val(coder);
        //distance2 = rangeD + "";
        //$("#distance").attr('value', distance2);
        //alert($("#distance").val());
       
        $('#centerlist_results').html('<div style="text-align: center;"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div>');
        $.ajax({
            type: "GET",
            url: "DealerSearchResult",
            async: true,
            data: "Manufacturer=0" + "&AreaCode=" + code + "&City=" + city + "&Range=" + rangeD + "&IsSearchCheckboxInd=false" + "&IsSearchCheckboxFahrhilfenn=false" + "&IsSearchCheckboxTransport=false",
            success: function (html) {
                 $("#centerlist_results").html(html);				 
                //initialize();
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#centerlist_results").html(textStatus);
            }
        });
    } else {
        $('#centerlist_results').show();
        $('#centerlist_results').html('<div class="errorHandlerPlz">Bitte PLZ oder Ort eingeben</div><div class="errorHandlerBox">&nbsp; </div>');
    }

}


$(document).ready(function () {    
    $('#search_dealer').submit(function (fn) {
        fn.preventDefault();
        var re = new RegExp(/^([0-9]){5}$/);
        var city = "";
        var cityNew = "" + "";
        var code = "";
        if ($('#code').val().match(re)) { code = $('#code').val(); }
        else {
            city = document.getElementById("code").value; //"hhhü"; //$('#code').val();
            cityNew = city.replace(String.fromCharCode(252), "ue").replace(String.fromCharCode(220), "Ue").replace(String.fromCharCode(228), "ae").replace(String.fromCharCode(196), "Ae").replace(String.fromCharCode(246), "oe").replace(String.fromCharCode(214), "Oe").replace(String.fromCharCode(223), "ss");
        }
        if ($('#code').val() != "") {
            $('#centerlist_results').show();
            $('#centerlist_results').html('<div style="text-align: center;"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div>');
            $.ajax({
                type: "GET",
                url: "/autonomy-center-haendler/DealerSearchResult",
                async: true,
                data: "Manufacturer=" + $('#manufacturer').val() + "&AreaCode=" + code + "&City=" + cityNew + "&Range=" + $('#distance').val() + "&IsSearchCheckboxInd=" + $("#individual").is(':checked') + "&IsSearchCheckboxFahrhilfenn=" + $("#assists").is(":checked") + "&IsSearchCheckboxTransport=" + $("#transport").is(":checked"),
                success: function (html) {
					if (html.indexOf("errorHandlerPlzOrt") == -1) 
					{
						trackingPixelHaendlersucheConfirmation();
					}
                    $("#centerlist_results").html(html);
                    //initialize();
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    $("#centerlist_results").html(textStatus);
                }
            });
        } else {
            $('#centerlist_results').show();
            $('#centerlist_results').html('<div class="errorHandlerPlz">Bitte PLZ oder Ort eingeben</div><div class="errorHandlerBox">&nbsp; </div>');
        }        

        return false;
    });

    $('#detail_tabs ul li a').each(function () {
        $(this).click(function (fn) {
            $('#detail_tabs ul li a').each(function () { $(this).removeClass("selected"); });
            $(this).toggleClass("selected");

            changeModelDrivingAid($(this).attr('href'));
            fn.preventDefault();
            return false;
        });
    });

    $('#matrix_tabs ul li a').each(function () {
        $(this).click(function (fn) {
            $('#matrix_tabs ul li a').each(function () { $(this).removeClass("selected"); });
            $(this).toggleClass("selected");

            changeManufacturer($(this).attr('href'));
            fn.preventDefault();
            return false;
        });
    });

    $('#LosungenDropBoxItem').change(function (fn) {
        fn.preventDefault();
        loadModels();
        return false;
    });
    $('#MarkenDropboxItems').change(function (fn) {
        fn.preventDefault();
        loadModels();
        return false;
    });
    setEventsHandlers();
    if (!fiatThemeCookie) {
        createCookie('fiattheme', 'white', 365);
        fiatThemeCookie = 'white';
    }
    if (fiatThemeCookie == 'textonly') {
        setTextOnly();


    } else {
        setTheme(fiatThemeCookie);
        //$("#accordion").accordion({ autoHeight: false, navigation: true });
        $("#accordion").accordion({ animated: false, autoHeight: false, navigation: true });

        var fiatFontSizeCookie = readCookie('fiatfontsize');
        if (!fiatFontSizeCookie) {
            createCookie('fiatfontsize', 'std', 365);
            fiatFontSizeCookie = 'std';

        }
        setFontSize(fiatFontSizeCookie);
    }


    $('#suche-input').click(function (fn) {
        if ($(this).val() == 'SUCHE')
            $(this).val('');
    });
    $('#suche-input').blur(function (fn) {
        if ($(this).val() == '')
            $(this).val('SUCHE');
    });

    //initializeLocation();

});

function loadModels() {
    $('#modelle_search_results').html('<div style="text-align: center;"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div>');
        $.ajax({
            type: "GET",
            url: "/fahrhilfen-modelle/Search",
            async: true,
            data: "ExpectedDrivingAidType=" + $('#LosungenDropBoxItem').val() + "&ExpectedManufacturerId=" + $('#MarkenDropboxItems').val(),
            success: function(html){
                $("#modelle_search_results").html(html);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#modelle_search_results").html(textStatus);
            }
    });
}

function changeModelDrivingAid(href) {
    $('#page_content').show();
    $('#page_content').html('<div style="text-align: center;"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div>');
        $.ajax({
            type: "GET",
            url: href,
            async: true,
            success: function(html){
                $("#page_content").html(html);
                $("#accordion").accordion({autoHeight: false,navigation: true});
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#page_content").html(textStatus);
            }
    });
}
function changeManufacturer(href) {
    $('#page_content').show();
    $('#page_content').html('<div style="text-align: center;"><img src="/Content/images/ajax-loader.gif" alt="Loading"/></div>');
        $.ajax({
            type: "GET",
            url: href,
            async: true,
            success: function(html){
                $("#page_content").html(html);
                $("#accordion").accordion({autoHeight: false,navigation: true});
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#page_content").html(textStatus);
            }
    });
}

function clearSuche() {
    $('#suche-input').val('');

}
function trackingPixelPreislisteConfirmation()
	{ 
		/* Activity Name for this tag is: Autonomy / Prospekt Magazin Preisliste Confirmation */
		var userInput = '<iframe src="http://gmads.net/pct?gmtevt=8a8386883515a540013562d08f9a38c4&gmtr=' + Math.floor(Math.random() * 9999999999) + '" style="overflow:hidden" frameborder="0" width="0" height="0"></iframe>';
		document.getElementById('customTrackingContainer').innerHTML = userInput;
		/* Activity End */
	
	}	
	
function trackingPixelHaendlersucheConfirmation()
	{ 
		/* Activity Name for this tag is: Autonomy / Haendlersuche Confirmation */
		var userInput = '<iframe src="http://gmads.net/pct?gmtevt=8a8386883515a540013562ceff4b3882&gmtr=' + Math.floor(Math.random() * 9999999999) + '" style="overflow:hidden" frameborder="0" width="0" height="0"></iframe>';
		document.getElementById('dealersearchTrackingContainer').innerHTML = userInput;
		/* Activity End */
	
	}	
	

