/**
 *  Copyright (C) 2007 Alness Software Ltd.
 *  All rights reserved.
 *
 *  $Id: navigation.js 2214 2009-12-16 13:24:58Z yexu $
 */

// Preload images, doesnt reduce loading time, but prevent load
// it again in subsequent pages
if (document.images) {
   //img1 = new Image();
   img2 = new Image();
   //img3 = new Image();
   //img4 = new Image();
   //img5 = new Image();
   //img6 = new Image();
   //img7 = new Image();
   //img8 = new Image();
   //img9 = new Image();
   //img10 = new Image();
   //img11 = new Image();
   //img12 = new Image();
   //img13 = new Image();
   img14 = new Image();
   img15 = new Image();
   img16 = new Image();
   img17 = new Image();
   img18 = new Image();
   //img1.src = "/img/te/round-corner-right-bottom.png";
   img2.src = "/img/te/trucks-europe-logo.png";
   //img3.src = "/img/te/Te-728x90.gif";
   //img4.src = "/img/icons/home.gif";
   //img5.src = "/img/icons/search.gif";
   //img6.src = "/img/icons/hilfe.gif";
   //img7.src = "/img/icons/information.gif";
   //img8.src = "/img/icons/parkplatz.gif";
   //img9.src = "/img/icons/anbieten.gif";
   //img10.src = "/img/te/round-corner-left-top.png";
   //img11.src = "/img/te/round-corner-right-top.png";
   //img12.src = "/img/te/round-corner-left-top-gray.png";
   //img13.src = "/img/te/round-corner-right-top-gray.png";
   img14.src = "/img/te/ajax-loader.gif";
   img15.src = "/img/te/nopic.png";
   img16.src = "/img/thickbox/loadingAnimation.gif";
   img17.src = "/img/treeview/tv-item.gif";
   img18.src = "/img/te/breadcrumb.gif";
}
var MAX_PIC=16;

$(document).ready(function() {
	// Initialize Quick login 
	$('#login-show').click(function() {
		$('#login-links').hide();
		$('#quick-login').show();
		return false;
	}).attr('href', '#');
    // initialize_rounder_corner();

    // Dynamic menu
    $("#search-submenu").hide();
    $(".search-menu").mouseover(function(event) {
        if ($("#search-submenu").css("display") == "none") {
            $("#search-submenu").show("slow");
        }
    });

    $("#offer-submenu").hide();

    $(".offer-menu").mouseover(function(event) {
        if ($("#offer-submenu").css("display") == "none") {
            $("#offer-submenu").show("slow");
        }
    });


    initialize_language_selector();
	initialize_main_menu();

	initialize_according_to_page();

    // For I-Icon
    initialize_info_icon();
	initialize_park_links();
    //only for ie6, shall put it into a seperate js file
	hack_ie_six_iframe();

    // check dup select
    //check_kat_auf_select();

    // init search results count
    init_search_count();
});

/* BEGIN search results count */
function init_search_count() {
    var url = window.location;
    var url_items = url.pathname.split("/");
    if (url_items.contains("search")) {
        search_count_ajax_loader();
        delay_update_search_count();
        // deal with detail dialog
        $(".thickbox").bind("click", function(event) {
            //console.log("details button...");
            setTimeout("", 1000);
            var is_clicked = false;
            $("#TB_ajaxContent").bind("click", function(event) {
                //console.log("details changes?...");
                if (check_if_trigger_handler(event)) {
                    is_clicked = true;
                }
            });
            $("#TB_ajaxContent .button").bind("click", function(event) {
                //console.log("detail button click, needs send update?...");
                if (is_clicked) {
                    delay_update_search_count();
                    is_clicked = false;
                    return false;
                }
            });
        });
        $("#main_form input:text").bind("keypress", function(event) {
            //console.log("detect textfield changes");
            setTimeout("", 2000);
            delay_update_search_count();
        });
        $("#main_form").bind("click", function(event) {
            check_if_trigger_handler(event);
            if (check_if_trigger_handler(event)) {
                delay_update_search_count();
            }
        });
    }
}

function check_if_trigger_handler(event) {
    var pre_sib = event.target.previousElementSibling;
    var trigger_element = event.target.tagName;
    if (trigger_element == 'INPUT' || trigger_element == 'OPTION' || pre_sib == 'INPUT') {
        //console.log("inside check event trigger");
        return true;
    } else {
        return false;
    }
}

function get_search_count_url() {
    //var url = window.location;
    var url = get_clean_url();
    //console.log(url);
    var form_results = $("#main_form").formHash();
    var search_query = parseUri(url).queryKey;
    //console.log(form_results);
    //console.log(parseUri(url).queryKey);
    // format the url?
    //var ajax_url = '?';
    var ajax_url = '';
    // only for url with search query, e.g. search got clicked from search results
    if (window.location.search) {
        //console.log("has search query");
        for (s_result in search_query) {
            if (search_query[s_result]) {
                //console.log(s_result) + " " + console.log(search_query[s_result]);
                form_results[s_result] = search_query[s_result];
            }
        }
    }
    //console.log(form_results);
    for (result in form_results) {
        ajax_url += result + '=' + form_results[result] + '&';
    }
    var query_url = ajax_url.slice(0, ajax_url.length-1)
    //console.log(query_url);
    return query_url;
}

function get_clean_url() {
    var url = window.location.protocol + "//" + window.location.host + 
              window.location.pathname;
    //console.log(url);
    return url;
}

function delay_update_search_count() {
    // ready to update button text? or don't need it anyhow
    show_search_count_loader();
    var delay_time = 2000;
    var has_search_button = $("#main_form:has(.side_submit_btn)").length
    //console.log("search button loaded? " + has_search_button);
    if (parseInt(has_search_button) > 0) {
        var url = url;
        setTimeout("send_search_count_ajax_req()", 2000);
    }
    return false;
}

function send_search_count_ajax_req() {
    var base_url = "/ajaxsrv/count_of";
    var query_url = get_search_count_url();
    // don't forget if textfield is true, includes it in query_url.
    //console.log('sending ajax request with ' + query_url + ' ...');
    $.ajax({
        type: "GET",
        url: base_url,
        data: query_url,
        success: function(msg){
            //console.log("get response from server...");
            //console.log(msg);
            //console.log(parseInt(msg));
            insert_search_count_on_button(msg);
        }
    });
}

function insert_search_count_on_button(result) {
    var button = $(".side_submit_btn input:submit")
    var button_val = button.val();
    //console.log(button_val);
    var button_len = button_val.split(" ");
    if (!isNaN(parseInt(result))) {
        // has previous value, if true, remove it
        if (button_len.length > 1) {
            button_val = button_len[button_len.length-1]
            //console.log(button_val);
        }
        button.val(result + " " + button_val);
    } else if (isNaN(parseInt(result)) && button_len.length > 1) {
        button_val = button_len[button_len.length-1]
        button.val(button_val);
    }
    hide_search_count_loader();
    //console.log('updating search count on button with ' + result + ' ...');
    //return false;
}

function search_count_ajax_loader() {
    //console.log($(".side_submit_btn ~ span"));
    ajax_loader = '<div class="search-count-loader"><img src="/img/te/search-count-loader.gif" alt="search-count-loading"/></div>';
    $(".side_submit_btn").prepend(ajax_loader);
}

function show_search_count_loader() {
    //console.log("show");
    $(".search-count-loader").show();
}

function hide_search_count_loader() {
    //console.log("hide");
    $(".search-count-loader").hide();
}
/* END search results count */

function initialize_according_to_page() {
	url_list = window.location.href.split("/");

    if (url_list.contains("expose")) {
        initialize_expose_thumbnails();
		if (url_list.contains("print"))
			init_no_printing();
    } else if (url_list.contains("offer")) {
		initialize_submit_buttons();
        picture_auto_uploading();
        initialize_offer_signalslot();
		initialize_details_links();
		// For Bemerkung Fieldset
		$("textarea[name='f549']").parent().addClass("fieldset");

    } else if (url_list.contains("search")) {
		initialize_submit_buttons();
        initialize_search_signalslot();
		initialize_details_links();
		if (url_list.contains("park"))
			init_park_details();
    } else if (url_list.contains("vehicles")) {
		// For all select in my vehicles page
		initialize_myvehicles_all_select();
	}

}

function initialize_details_links() {
	$('a.thickbox').click(function() {
		$('#TB_ajaxContent :input').removeAttr('disabled');
	});
}

function hack_ie_six_iframe(){
    $(".help-text").bgiframe();
    $("#main-menu ul").bgiframe();
}

function hack_pkw_alle () {
    // according to the url, see if the hack shall be applied
    var url = window.location.pathname;
    var url_item = url.split("/");
    var isoffer = url_item[1];
    var value418 = url_item[2];
    var ifstop = url_item[3];
    // hack pkw
    if (value418 != "offer") {
        $('#main_form_w1214_w9105').change(
        function(){
            var aufval = $('#main_form_w1214_w9105 :selected').val();    
            if (url_item[2] != "pattern"){
                window.location = [url_item[0], isoffer, value418, aufval].join('/');
            }
        });
    }
    // hack selbstfahrend, anbau and wohnmobile
    $('#main_form_w1214_w418').change(
    function(){
        var aufval = $('#main_form_w1214_w418 :selected').val();
        window.location = [url_item[0], isoffer, aufval].join('/');
        // special for wohnmobile
        //if (aufval == "7410") {
        //    window.location = [url_item[0], isoffer, aufval, "7583"].join('/');
        //} else {
        //    // for the other
        //    window.location = [url_item[0], isoffer, aufval].join('/');
        //}
    });
}

function initialize_vehicle_count() {
	refresh_vehicle_count();
	$("#main_form :input").change(refresh_vehicle_count);
}

function refresh_vehicle_count() {
	var category = $("select[slot='kat']").val();
	if (category) {
		var queries = $("#maim_form").serialize();
		$.getJSON('/ajaxsrv/count_of/?'+queries,
			function(data) {
				if (isInt(data)) {
					$("input.submitbutton").val("Treffer anzeigen: "+data);
				}
			}
		);
	}
}

Array.prototype.remove=function(s) {
    for(i=0;i<this.length;i++) {
        if(s==this[i]) this.splice(i, 1);
    }
}

Array.prototype.contains=function(s) {
    for(i=0;i<this.length;i++) {
        if(s==this[i]) return true;
    }
    return false;
}

String.prototype.zfill=function(width) {
    var str = '' + this;
    while (str.length < width) str = '0' + str;
    return str;
}

/*****
 * Signal & Slot declaration
 *****/
function initialize_search_signalslot() {
    function getFromToWidget(fid) {
        return $("." + fid + " div").extend({
            getFrom: function() {
                         if ($(this).length != 0) {
                            return $($(this).children()[1]);
                         } else {
                            return $([]);
                         }
                     },
            getTo: function() {
                       if ($(this).length != 0) {
                           return $($(this).children()[3]);
                       } else {
                           return $([]);
                       }
                   }
        });
    }

    var basisZu = $(".f_id-9133");
    var erstzulassung = getFromToWidget("f_id-319");
    var baujahr = getFromToWidget("f_id-427");

    if (basisZu.val() == "12148") {
        erstzulassung.getFrom().attr("disabled", true);
        erstzulassung.getTo().attr("disabled", true);
    }

    /*
     * BasisZulassung Neu
     */
    var SIG_BZ_NEU = 'bz_neu';
    var opts_bz_neu = {
        evt: 'change', 
        prefunc: function() {
                     return $(this).val() == '12148';
                 }
    };
    basisZu.signal(SIG_BZ_NEU, '', opts_bz_neu);
    var bz_neu_cb = function() {
        $(this).val("");
        $(this).attr("disabled", true);
    };
    erstzulassung.getFrom().slot(SIG_BZ_NEU, bz_neu_cb);
    erstzulassung.getTo().slot(SIG_BZ_NEU, bz_neu_cb);
    
    /*
     * BasisZulassung Reset
     */
    var SIG_BZ_RESET = 'bz_reset';
    var opts_bz_reset = {
        evt:'change',
        prefunc: function() {
                     return $(this).val() != '12148';
                 }
    };
    var bz_reset_cb = function() {
        $(this).attr("disabled", false);
    };
    basisZu.signal(SIG_BZ_RESET, '', opts_bz_reset);
    erstzulassung.getFrom().slot(SIG_BZ_RESET, bz_reset_cb);
    erstzulassung.getTo().slot(SIG_BZ_RESET, bz_reset_cb);
}

function initialize_offer_signalslot() {
    // Commmon class for TextWhenRequired widget
    function getTextWhenRequiredWidget(fid) {
        return  $("." + fid + " div").extend({

            getInput: function() {
				if ($(this).length != 0) {
					return $($(this).children()[2]);
				} else {
					return $([]);
				}
			},

            getOptional: function() {
				if ($(this).length != 0) {
					return $($(this).children()[1]);
				} else {
					return $([]);
				}
			},

			setRequired: function() {
				var my_id = $(this).attr('id');
				var optional = $('#'+my_id+'_optional');
				var input = $('#'+my_id+'_input');
				if (optional)
					optional.val(''); // Not optional
				if (input)
					input.addClass('required');
			},

			setOptional: function () {
				var my_id = $(this).attr('id');
				var optional = $('#'+my_id+'_optional');
				var input = $('#'+my_id+'_input');
				if (optional)
					optional.val('True');
				if (input)
					input.removeClass('required');
			}
			
					
        });
    }

    // Basis Zulassung for LKW, PKW...
    var basisZu_LKW = $(".f_id-9133");
    // var basisZu_SF = $(".f_id-20452");
    var basisZu_SF = $(".f_id-9133");
    // allgemain case
    var basisZu_geb_Dtl = $(".f_id-146");
    var erstzulassung = $(".f_id-319 div").extend({
        getYear: function() {
                     if ($(this).length != 0) {
                         return $($(this).children()[4]);
                     } else {
                         return $([]);
                     }
                 },
        getOptional: function() {
                         if ($(this).length != 0) {
                             return $($(this).children()[1]);
                         } else {
                             return $([]);
                         }
                     },
        getMonth: function() {
                      if ($(this).length != 0) {
                          return $($(this).children()[2]);
                      } else {
                          return $([]);
                      }
                  }
    });
    var baujahr = getTextWhenRequiredWidget("f_id-427");
    var bisher_zugelassen = $(".f_id-9086");

	/*
	 * HU Like
	 */
    var HULikeArrays = $(".HULike").map(function() {
        return $($(this).parent()).extend({
            getYear: function() {
                         if ($(this).length != 0) {
                            return $($(this).children()[3]);
                         } else {
                            return $([]);
                         }
                     },
            getMonth: function() {
                          if ($(this).length != 0) {
                              return $($(this).children()[1]);
                          } else {
                              return $([]); 
                          }
                     }
        });
    });

    /*
     *Initial Erstzulassung display
     */
    if ((basisZu_LKW.val() == "12148") || (basisZu_geb_Dtl.val() == "20455")) {
            erstzulassung.getYear().removeClass("required");
            erstzulassung.getYear().attr("disabled", true);
            erstzulassung.getMonth().attr("disabled", true);
            erstzulassung.getOptional().val("True");
			baujahr.setRequired();
    } else {
            erstzulassung.getOptional().val("");
            baujahr.getOptional().val("True");
    }

    /*
     * BasisZulassung with Neu
     */
    var SIG_BasisZulassung_Neu_LKW = 'offer_bz_neu_lkw';
    var opts0 = {
        evt: 'change',
        prefunc: function() {
                     return $(this).val() == '12148';
                 }
    }
    basisZu_LKW.signal(
            SIG_BasisZulassung_Neu_LKW,
            '', opts0);
    erstzulassung.getYear().slot(
            SIG_BasisZulassung_Neu_LKW,
            function() {
                $(this).removeClass('required');
                $(this).val("");
                $(this).attr("disabled", true);
                erstzulassung.getMonth().val("");
                erstzulassung.getMonth().attr("disabled", true);
                $(this).prev().prev().prev().val("True");
                $(this).next().empty();
            });
    baujahr.getInput().slot(
            SIG_BasisZulassung_Neu_LKW,
            function() {
                $('#'+$(this).attr("id")).attr("class", "simpletextfield required");
                $(this).prev().val("");
            });
    $(HULikeArrays).each(function() {
            this.getYear().slot(
                SIG_BasisZulassung_Neu_LKW,
                function() {
                    if (bisher_zugelassen.val() != "") {
                        $(this).val("9999-01-01");
                        expr = $(this).parent().parent().attr("id").split("_")[2];
                        $(".thickbox[href*='" + expr + "']").css("color", "#FF9921");
                    }
                });
            this.getMonth().slot(
                SIG_BasisZulassung_Neu_LKW,
                function() {
                    if (bisher_zugelassen.val() != "") {
                        $(this).val("");
                        $(this).attr("disabled", true);
                    }
                });
    });

    var SIG_BasisZulassung_Neu_SF = 'offer_bz_new_sf';
    var opts1 = {
        evt: 'change',
        prefunc: function() {
            return $(this).val() == '12148';
        }
    }
    basisZu_SF.signal(
            SIG_BasisZulassung_Neu_SF,
            '', opts1);
    baujahr.getInput().slot(
            SIG_BasisZulassung_Neu_SF,
            function() {
                $(this).prev().val("True");
                $(this).next().empty();
            });
    $(HULikeArrays).each(function() {
            this.getYear().slot(
                SIG_BasisZulassung_Neu_SF,
                function() {
                    if (bisher_zugelassen.val() != "") {
                        $(this).val("9999-01-01");
                        expr = $(this).parent().parent().attr("id").split("_")[2];
                        $(".thickbox[href*='" + expr + "']").css("color", "#FF9921");
                    }
                });
            this.getMonth().slot(
                SIG_BasisZulassung_Neu_SF,
                function() {
                    if (bisher_zugelassen.val() != "") {
                        $(this).val("");
                        $(this).attr("disabled", true);
                    }
                });
    });

    var SIG_BasisZulassung_Gebraucht_KeineZU = 'offer_bz_geb_kein';
    var opts2 = {
        evt: 'change',
        prefunc: function() {
                     return $(this).val() == '20455';
                 }
    }
    basisZu_geb_Dtl.signal(
            SIG_BasisZulassung_Gebraucht_KeineZU,
            '',opts2);
    erstzulassung.getYear().slot(
            SIG_BasisZulassung_Gebraucht_KeineZU,
            function() { 
                $(this).removeClass("required");
                $(this).val("");
                $(this).attr("disabled", true);
                erstzulassung.getMonth().attr("disabled", true);
                erstzulassung.getMonth().val("");
                $(this).prev().prev().prev().val("True");
                $(this).next().empty();
            });
    baujahr.getInput().slot(
            SIG_BasisZulassung_Gebraucht_KeineZU,
            function() {
                $(this).addClass("required");
                $(this).prev().val("");
            });
    /*
    $(HULikeArrays).each(function() {
            this.getYear().slot(
                SIG_BasisZulassung_Gebraucht_KeineZU,
                function() {
                    $(this).val("");
                    expr = $(this).parent().parent().attr("id").split("_")[2];
                    $(".thickbox[href*='" + expr + "']").css("color", "#000099");
                });
            this.getMonth().slot(
                SIG_BasisZulassung_Gebraucht_KeineZU,
                function() {
                    $(this).attr("disabled", false);
                });
    });
    */


    /*
     * BasisZulassung ReSet
     */
    var SIG_BasisZulassung_LKW_Reset = 'offer_bz_lkw_reset';
    var opts3 = {
        evt: 'change',
        prefunc: function() {
                     return $(this).val() != '12148';
                 }
    };
    basisZu_LKW.signal(
            SIG_BasisZulassung_LKW_Reset,
            '', opts3);
    erstzulassung.getYear().slot(
            SIG_BasisZulassung_LKW_Reset,
            function() {
                $(this).addClass('required');
                erstzulassung.getOptional().val("");
                erstzulassung.getMonth().attr('disabled', false);
                $(this).attr("disabled", false);
            });
    baujahr.getInput().slot(
            SIG_BasisZulassung_LKW_Reset,
            function() {
                $(this).removeClass('required');
                $(this).prev().val("True");
                $(this).next().empty();
            });
    $(HULikeArrays).each(function() {
            this.getYear().slot(
                SIG_BasisZulassung_LKW_Reset,
                function() {
                    $(this).val("");
                    expr = $(this).parent().parent().attr("id").split("_")[2];
                    $(".thickbox[href*='" + expr + "']").css("color", "#000099");
                });
            this.getMonth().slot(
                SIG_BasisZulassung_LKW_Reset,
                function() {
                    $(this).attr("disabled", false);
                });
    });

    var SIG_BasisZulassung_SF_Reset = 'offer_bz_sf_reset';
    var opts4 = {
        evt: 'change',
        prefunc: function() {
            return $(this).val() != '12148';
        }
    }
    basisZu_SF.signal(
            SIG_BasisZulassung_SF_Reset,
            '', opts4);
    baujahr.getInput().slot(
            SIG_BasisZulassung_SF_Reset,
            function() {
                $(this).prev().val('');
            });
    $(HULikeArrays).each(function() {
            this.getYear().slot(
                SIG_BasisZulassung_SF_Reset,
                function() {
                    $(this).val("");
                    expr = $(this).parent().parent().attr("id").split("_")[2];
                    $(".thickbox[href*='" + expr + "']").css("color", "#000099");
                });
            this.getMonth().slot(
                SIG_BasisZulassung_SF_Reset,
                function() {
                    $(this).attr("disabled", false);
                });

    });

    var SIG_BasisZulassung_DTL_Reset = 'offer_bz_dtl_reset';
    var opts5 = {
        evt: 'change',
        prefunc: function() {
            return $(this).val() != '20455';
        }
    }
    basisZu_geb_Dtl.signal(
            SIG_BasisZulassung_DTL_Reset,
            '', opts5);
    erstzulassung.getYear().slot(
            SIG_BasisZulassung_DTL_Reset,
            function() {
                $(this).addClass('required');
                $(this).attr('disabled', false);
                erstzulassung.getMonth().attr('disabled', false);
                $(this).prev().prev().prev().val("");
            });
    baujahr.getInput().slot(
            SIG_BasisZulassung_DTL_Reset,
            function() {
                $(this).removeClass('required');
                $(this).prev().val("True");
            });

    // initialize HULike
    $(HULikeArrays).each(function() {
            if (this.getYear().val() == '9999-01-01') {
                this.getMonth().attr("disabled", true);
            }
            var SIG_X = this.getYear().attr("id");
            var opts_new = {
                evt: 'change',
                prefunc: function() {
                    return $(this).val() == '9999-01-01';
                }
            };
            var opts_not_new = {
                evt: 'change',
                prefunc: function() {
                    return $(this).val() != '9999-01-01';
                }
            };
            this.getYear().signal(
                SIG_X + '_new',
                '', opts_new);
            this.getMonth().slot(
                SIG_X + '_new', 
                function() {
                    $(this).val("");
                    $(this).attr("disabled", true);
                });
            this.getYear().signal(
                    SIG_X + '_not_new',
                    '', opts_not_new);
            this.getMonth().slot(
                    SIG_X + '_not_new',
                    function() {
                        $(this).attr("disabled", false);
                    });
    });
}
/***** End *****/


function initialize_info_icon() {
    $(".iicon").each(
        function() {
            $(this).jHelperTip({
                trigger: "click",
                dC: "#" + $(this).next().attr("id"),
                autoClose: false,
                opacity: 0.9
            });
        }
    );
}


function initialize_myvehicles_all_select() {
    $("input[name='selectall']").change(
        function() {
            if ($(this).attr("checked") == true) {
                $(".searchresultitem li.vehicle-select > input").attr("checked", true);
                $("input[name='selectall']").attr("checked", true);
            } else {
                $(".searchresultitem li.vehicle-select > input").attr("checked", false);
                $("input[name='selectall']").attr("checked", false);
            }
        }
    );

    $("#myvehicles-toolbox").submit(
        function() {
            var selected_vehicles_str = "";
            var selected_vehicles = $("input:checked[name!='selectall']");
            if (selected_vehicles.length != 0) {
                for(i = 0; i < selected_vehicles.length; i++) {
                    selected_vehicles_str += $(selected_vehicles[i]).val() + "|";
                }
                $("#selectedvehicles").val(selected_vehicles_str);
                return true;
            } else {
                return false;
            }
        }
    );
}

function initialize_submit_buttons() {
    var patharray = window.location.href.split("/");

    if ((patharray.contains("search")) || ((patharray.contains("offer")) && !isNaN(parseInt(patharray[5]))) || (patharray.contains("pattern"))) {
    	var label = $("#main_form_offer,#main_form_search").val();
    	$("#main_form > div > div.fieldset > h4 > span").append(
	    "<div class='side_submit_btn' style='float:right;" +
            "margin-right: .2em; margin-bottom: .2em;'><input class='submitbutton' style='padding:0;margin:0;' type='submit' value=" +
            "'" + label + "' /></div>"
		);
    }
	if (patharray.contains("offer")) {
		var url = window.location.href.split("?")[0];
		var label = 'Formular leeren';
		if (patharray.contains("edit"))
			label = 'Formular zurücksetzen';
		$("#main_form > div > div.classificationfieldset > h4 > span").append(
		"<div class='side_submit_btn' style='float:right;" +
			"margin-right: .2em; margin-bottom: .2em;'><a class='button' style='padding:0 .2em;margin:0;' href=" +
			"'" + url + "' onclick='return confirm(\"Sind Sie sicher?\");'>"+ label +"</a></div>"
		);
	}
	//initialize_vehicle_count();
}

function initialize_main_menu() {
	$(".menu>ul>li>ul").css({display: "none"}); // Opera Fix
	$(".menu li").hover(function(){
		$(this).find('ul:first').css({visibility: "visible",display: "none", "z-index": "999"}).show(400);
		},function(){
		$(this).find('ul:first').css({visibility: "hidden"});
		});
}

function w515_callback(evt) {
    var ll, nn, gg, gewicht, leergew, nutzlst;
    ll = $("input[name='f324']");
    nn = $("input[name='f325']");
    gg = $("input[name='f323']");
    leergew = parseInt(ll.eq(0).val());
    nutzlst = parseInt(nn.eq(0).val());
    gewicht = parseInt(gg.eq(0).val());
    leergew = isNaN(leergew) ? 0: leergew
    nutzlst = isNaN(nutzlst) ? 0: nutzlst
    gewicht = isNaN(gewicht) ? 0: gewicht

    if (isNaN(gewicht)) {
        gewicht = leergew + nutzlst;
    } else {
        if (gewicht < leergew)
            leergew = gewicht;
        nutzlst = gewicht - leergew;
    }
    leergew = (leergew == 0) ? '': leergew;
    nutzlst = (nutzlst == 0) ? '': nutzlst;
    gewicht = (gewicht == 0) ? '': gewicht;
    nn.val(nutzlst);
    ll.val(leergew);
    gg.val(gewicht);
}
function w613_callback(evt) {
    var ll, nn, gg, gewicht, leergew, nutzlst;
	ll = $("input[name='f324']");
	nn = $("input[name='f325']");
	gg = $("input[name='f323']");
    leergew = parseInt(ll.eq(0).val());
    nutzlst = parseInt(nn.eq(0).val());
    gewicht = parseInt(gg.eq(0).val());
    leergew = isNaN(leergew) ? 0: leergew
    nutzlst = isNaN(nutzlst) ? 0: nutzlst
    gewicht = isNaN(gewicht) ? 0: gewicht

    if (isNaN(gewicht)) {
        gewicht = leergew + nutzlst
    } else {
        if (gewicht < nutzlst)
            nutzlst = gewicht;
        leergew = gewicht - nutzlst
    }
    leergew = (leergew == 0) ? '': leergew;
    nutzlst = (nutzlst == 0) ? '': nutzlst;
    gewicht = (gewicht == 0) ? '': gewicht;
    nn.val(nutzlst);
    ll.val(leergew);
    gg.val(gewicht);
}
function w314_callback(evt) {
    var ll, nn, gg, gewicht, leergew, nutzlst;
	ll = $("input[name='f324']");
	nn = $("input[name='f325']");
	gg = $("input[name='f323']");
    leergew = parseInt(ll.eq(0).val());
    nutzlst = parseInt(nn.eq(0).val());
    gewicht = parseInt(gg.eq(0).val());
    leergew = isNaN(leergew) ? 0: leergew
    nutzlst = isNaN(nutzlst) ? 0: nutzlst
    gewicht = isNaN(gewicht) ? 0: gewicht

    if (isNaN(leergew) && !isNaN(nutzlst)) {
        if (gewicht < nutzlst)
            nutzlst = gewicht;
        leergew = gewicht - nutzlst;
    } else if (leergew != 0) {
        if (gewicht < leergew)
            leergew = gewicht;
        nutzlst = gewicht - leergew;
    }
    leergew = (leergew == 0) ? '': leergew;
    nutzlst = (nutzlst == 0) ? '': nutzlst;
    nn.val(nutzlst);
    ll.val(leergew);
}

//function w106_ready_callback() {
    ////alert("w106 active");
    //// Einstufung Loading
    //var url = window.location.href;
    //var url_item = url.split("/");
    //var kat = $("select[slot='kat']");
    //var afb = $("select[slot='aufbau']");
    //var value418 = kat.val()
    //var value106 = afb.val()
    //if (value418 == '')
        //value418 = $(url_item).get(4)
    //if (value106 == '')
        //value106 = $(url_item).get(5)
    //// If value == '', then equal NaN
    //value106 = (value106 == '') ? NaN : value106;
    //value418 = (value418 == '') ? NaN : value418;
    ////alert(value418);
    ////alert(value106);
    
    //kat.val(value418);
    //if (isNaN(value418) == false) {
        //get_url = "/ajaxsrv/subclass/" + value418 + "/";
        //$.getJSON(get_url, function(data) {
                //var options = '<option value=""> ----- </option>';
                //$(data.subclasses).each(function (i) {
                    //options += '<option value="' + data.subclasses[i][0] +
                               //'">' + data.subclasses[i][1] + '</option>';
                    ////alert(i);
                //});
                ////alert(options);
                //afb.html(options);
                //afb.val("");
        //});
    //}

    //if (isNaN(value106) == false) {
        //afb.ajaxComplete(function(request, settings) {
            //$(this).val(value106);
        //});
    //}

    ////XXX
    //if (isNaN(value418) == true) {
        //afb.attr("disabled","disabled");
    //}
//}

function w106_callback(evt) {
	var path = window.location.pathname.split("/");
	var category = $("select[slot='kat']").val();
	var aufbau = $("select[slot='aufbau']").val();
	if (path[1] == 'offer') {
		// Submit if we are offering, in order to keep all the field changes
		var main_form = $('#main_form');
		if (path[2] != 'edit')
			main_form.attr({'action': [path[0], path[1], category, aufbau].join("/")});
		//else
			//main_form.attr({'action': [path[0], path[1],path[2], path[3]].join("/")});
		$('#tmp_fields > :input').removeAttr('disabled');
		main_form.attr({'method': 'get'}).submit();
	} else {
		// Don't need to keep the fields, so just change the url
		if (!isNaN(aufbau))
			window.location.pathname = [path[0], path[1], category, aufbau].join("/");
		else
			window.location.pathname = [path[0], path[1], category].join("/");
	}
}

function w418_callback(evt) {
	w106_callback(evt);
}
function w9105_callback(evt) {
	w106_callback(evt);
}

function power_ready_callback(id) {
    var target = $("#" + id);
    target.attr("slot", "leistung");
    target.numeric({allow:"."});
    target.parent().append("<span style='margin-left: .5em; clear: left;'" +
                            " slot='leistung'></span>");
    $("span[slot='leistung']").hide();
    $("#main_form").submit(
        function() {
            var type, ltg, float_, abs;
            type = $("select[slot='leistung-type'] option:selected").attr("value");
            if (type == 1) {
                ltg = parseInt($("input[slot='leistung']").val());
                if (!isNaN(ltg)) {
                    float_ = ltg / 1.359622;
                    abs = Math.round(
                        float_ * Math.pow(10, 0)
                    ) / Math.pow(10, 0);
                    $("select[slot='leistung-type']").val('0');
                    $("input[slot='leistung']").attr("value", abs);
                }
            }
        }
    );
    // get the details fieldset for the power fieldset
    // var dtl_f = $("#" + id.slice(0, -6) + "-label a.thickbox").attr("href").split("&")[1].slice(9,-1);
}

function power_callback(evt) {
    var target, ltg, flt, abs, type;
    if (evt.type == "keyup") {
        target = $(evt.target);
        type = target.siblings('select[name$="type"').eq(0).val();
    } else {
        target = $(evt.target).prev();
        type = $(evt.target).val();
    }
    ltg = parseInt(target.val())
    ltg = isNaN(ltg) ? 0: ltg;
    if (type == 0) {
        flt = ltg * 1.359622;
    } else {
        flt = ltg / 1.359622;
    }
    abs = Math.round(
        flt * Math.pow(10, 0)
    ) / Math.pow(10, 0);
    if (abs != 0) {
        if (type == 0) {
            $("span[slot='leistung']").text(abs + " PS");
        } else {
            $("span[slot='leistung']").text(abs + " KW");
        }
        if ($("span[slot='leistung']").css("display") == "none") {
            $("span[slot='leistung']").show("slow");
        }
    } else {
        $("span[slot='leistung']").hide("slow");
    }
}


function check_for_details_children(target) {
    var empty = true;
    $("#" + target + " div input:checkbox").each(
        function() {
            if ($(this).attr("checked") == true) {
                empty = false;
            }
        }
    );
    $("#" + target + " div select").each(
        function() {
            if ($(this).val() != '') {
                empty = false;
            }
        }
    );
    $("#" + target + " div input:text").each(
        function() {
            if ($(this).val() != '') {
                empty = false;
            }
        }
    );
    return empty;
}

function check_for_details_children_fielderror(target) {
    var haserror = false;
    // $("#" + target + " div").children("input:checkbox").each(
        // function() {
            // if ($(this).next().hasClass("fielderror")) {
                // haserror = true;
            // }
        // }
    // );

    // $("#" + target + " div").children("select").each(
        // function() {
            // if ($(this).next().hasClass("fielderror")) {
                // haserror = true;
            // }
        // }
    // );

    // $("#" + target + " div").children("input:text").each(
        // function() {
            // if ($(this).next().hasClass("fielderror")) {
                // haserror = true;
            // }
        // }
    // );
    
    // alert("#" + target + "div" + "|" + $("#" + target + " div").children(".fielderror").length);
    if ($("#" + target + " div .fielderror").length > 0) {
        haserror = true;
    }
    return haserror;
}

function initial_select_with_details(id, details) {
    $(
        function(event) {
            if ($("#" + id).val() != '') {
                var target = $(details).attr($("#" + id).val());
                $("#" + id + "-label").children("a[href*=" + target + "]").show();
				$("#main_form .detailsfieldset :input[id*="+target+"]").removeAttr('disabled');
            }
        }
    );
}

function details_js_loader_callback(id, _id) {
    $("#" + id).change(
        // details_js_loader_change_callback(id, _id)
        function(event) {
            // var value = $("#" + id).val();
            // if (value == '') {
                $("#" + id + "-wrapper a").css("color", "#000099");
                $(":input[slot='dtl_c_" + _id + "']").each(
                    function() {
                        $(this).attr('disabled', 'disabled').val('');
                    }
                );
                $(":checkbox[slot='dtl_c_" + _id + "']").each(
                    function() {
                        $(this).attr("checked", "");
                    }
                );
            // }
        }
    );
}

function details_children_widget_js_loader_callback(id, p_id, _p_id) {
    $("#" + id + " :input").each(
        function() {
            $(this).attr("slot", "dtl_c_" + _p_id);
            $(this).change(
                function(event) {
                    var empty = check_for_details_children("TB_ajaxContent");
                    if (empty == true) {
                        $("#" + p_id + "-label a").css("color", "#000099");
                    } else {
                        $("#" + p_id + "-label a").css("color", "#FF9921");
                    }

                    var c = $(this).attr("class");
                    var value;
                    if (c.split(" ").contains("checkbox")) {
                        value = $(this).attr("checked");
                    } else {
                        value = $(this).val();
                    }
                    $("*[class='" + c + "']").each(
                        function() {
                            if ($(this).attr("class").split(" ").contains("checkbox")) {
                                $(this).attr("checked", isNaN(value)?"":value);
                            } else {
                                $(this).val(value);
                            }
                        }
                    );
                }
            );
        }
    );
    $("#" + id).ready(
        function(event) {
            // if (window.location.href.split("/").contains("edit")) {
                var empty = check_for_details_children(id);
                var haserror = check_for_details_children_fielderror(id);
                if (empty == false) {
                    $("#" + p_id + "-label a").css("color", "#FF9921");
                }
                if (haserror == true) {
                    $("#" + p_id + "-label a").css("color", "#FF0000");
                    $("#" + p_id + "-label").parent().
                        append("<em class='details-error fielderror'>Fehler im Detail Fenster</em>");
                }
            // }
        }
    );
}

function checkbox_details_js_loader_callback(id, _id) {
    $("#" + id).attr("slot", "dtl_p_" + _id);
    $("#" + id).change(
        function(event) {
            var value = $("#" + id).attr("checked");
            if (value != true) {
                $("#" + id + "-wrapper a").css("color", "#000099");
                $(":input[slot='dtl_c_" + _id + "']").each(
                    function() {
                        $(this).val("");
                    }
                );
                $(":checkbox[slot='dtl_c_" + _id + "']").each(
                    function() {
                        // $(this).attr("checked", "");
                        $(this).attr("checked", false);
                    }
                );
            }
        }
    );
}

function checkbox_details_children_widget_js_loader_callback(id, p_id, _p_id) {
    $("#" + id + " :input").each(
        function() {
            $(this).attr("slot", "dtl_c_" + _p_id);
            $(this).change(
                function(event) {
                    var empty = check_for_details_children("TB_ajaxContent");
                    if (empty == true) {
                        $("#" + p_id).attr("checked", false);
                        $("#" + p_id + "-wrapper a").css("color", "#000099");
                    } else {
                        $("#" + p_id).attr("checked", true);
                        $("#" + p_id + "-wrapper a").css("color", "#FF9921");
                    }
                }
            );
        }
    );
    $("#" + id).ready(
        function(event) {
            // if (window.location.href.split("/").contains("edit")) {
                var empty = check_for_details_children(id);
                var haserror = check_for_details_children_fielderror(id);
                if (empty == false) {
                    $("#" + p_id + "-wrapper a").css("color", "#FF9921");
                }
                if (haserror == true) {
                    $("#" + p_id + "-wrapper a").css("color", "#FF0000");
                    $("#" + p_id + "-wrapper > div").
                        append("<em class='fielderror'>Fehler im Detail Fenster</em>");
                }
            // }
        }
    );
}

function picture_auto_uploading() {
    $("#main_form").submit(
        function() {
            for (var i = 0; i < MAX_PIC; i++) {
                if ($("#upload-" + i).val() != "") {
                    // alert($("#upload-" + i).val());
                    $("#upload-" + i).val("");
                }
            }
            var upload_number;
            upload_number = parseInt($("#upload_number").val());
            if (($("#main_form_w1704_upload_field").val() != "") && (upload_number < MAX_PIC)) {
                $("#main_form_w1704_upload_button").unbind("click", 
                                                   upload_image_fieldset_click_callback);
                $("#main_form_w1704_upload_button").bind("click",
                                                   upload_image_fieldset_click_callback_overload);
                $("#main_form_w1704_upload_button").click();
                // return false;
            } else {
                $("#main_form_w1704_upload_field").val("");
            }
            // return false;
        }
    );
}

// Overload the upload field click event callback func
function upload_image_fieldset_click_callback_overload() {
    alert("Your selected picture was uploaded");
    return false;
}

function upload_image_fieldset_ready_callback(id) {
    $("#loading").hide();
    $("#loading").ajaxStart(function(){
        $("#loading").show();
        $("#upload-message").hide();
    })
    $("#loading").ajaxComplete(function(){
        $("#loading").hide();
    });
    $("#" + id + "_upload_field").attr("name", "upload");
    $("#" + id + "_upload_id").attr("name", "upload_id");
    $("#upload-message").hide();
    for (var i = 0; i < MAX_PIC; i++) {
        initialize_update_image_fieldset(i);
    }
}

function initialize_update_image_fieldset(i) {
    function get_user_dir(uid) {
        var filled = uid;
        if (uid.length < MAX_PIC) {
            filled = uid.zfill(6);
        }
        return "/uploads/users/" + filled.slice(-2) + "/" + filled.slice(-4, -2) + "/" + filled.slice(0, -4) + "/" + uid;
    }

    if (!window.location.href.split("/").contains("pattern")) {
        var upload_number, upload_id, user_dir;
        upload_number = parseInt($("#upload_number").val());
        upload_id = $("input[name$='upload_id']").val();
        upload_uid = $("#upload_uid").val();
        user_dir = get_user_dir(upload_uid);

        if ((upload_number == 0) || (i > (upload_number - 1))) {
            $("#uploaded-" + i).hide();
        } else {
            if ($("#removebtn-" + i).attr("status") == '1') {
                $("#picture-" + i).attr("src", "/img/te/nopic.png");
            } else {
                $("#picture-" + i).attr("src", user_dir + "/tmp/"
                                           + upload_id + "_" + i + "_thumbnail.jpg");
            }
            // per .ajax check if the image thumbnail exist...
            $.ajax({
                url: user_dir + "/tmp/" + upload_id + "_" + i + "_thumbnail.jpg",
                cache: false,
                success: function() { },
                error: function() { 
                    $("#picture-" + i).attr("src", "/img/te/nopic.png"); 
                    // $("#picture-" + i).hide();
                    // $("#picture-" + i).show();
                }
            });
        }
    } else {
        $("#uploaded-" + i).hide();
        $("#upload_number").val("0");
    }

    $("#removebtn-" + i).click(function(event) {
        $("#loading").show();
        $("#upload-message").hide();
        imgsrc = $("#picture-" + i).attr("src").split("/")[8]
        $.post(
            "/form/ajax_remove_picture/",
            {
                fn: imgsrc
            },
            function(data, textStatus) {
                $("#loading").show();
                var dataArray = data.split("_")
                var status = dataArray[0]
                var message = dataArray[1]
                if (status == 'error') {
                    $("#upload-message").html(message);
                    $("#upload-message").attr("class", "fielderror");
                    $("#upload-message").show("slow");
                } else {
                    $("#picture-" + i).attr("src", "/img/te/nopic.png");
                    $("#uploaded-filename-" + i).html('');
                    $("#removebtn-" + i).attr("status", "1");
                    $("#upload-message").html(message);
                    $("#upload-message").attr("class", "notify");
                    $("#upload-message").show("slow");
                }
                /*
                if (typeof(data.error) != 'undefined') {
                    $("#upload-message").html(data.error);
                    $("#upload-message").attr("class", "fielderror");
                    $("#upload-message").show("slow");
                } else {
                    $("#picture-%i").attr("src", "/img/te/nopic.png");
                    $("#uploaded-filename-%i").html('');
                    $("#upload-message").html(data.msg);
                    $("#upload-message").attr("class", "notify");
                    $("#upload-message").show("slow");
                }
                */
            });
    });
    $("#uploadbtn-" + i).click(function(event) {
        $.ajaxFileUpload
        (
            {
                url: '/form/ajax_upload_picture/',
                secureuri: false,
                fileElementId: 'upload-' + i,
                dataType: 'json',
                success: function(data, status) {
                    if (typeof(data.error) != 'undefined') {
                        $("#upload-message").html(data.error);
                        $("#upload-message").attr("class", "fielderror");
                        $("#upload-message").show("slow");
                    } else {
                        $("#upload-" + i).val("");
                        // $("#picture-" + i).attr("src", "");
                        // XXX
                        // $("#picture-" + i).attr("src", "/" + data.path.replace(/\-/g,'\\-'));
                        // $("#picture-" + i).attr("src", "/" + data.path.replace(/\-/g,'\-'));
                        $("#picture-" + i).attr("src", "/" + data.path);
                        // $("#uploaded-" + i + " div.uploaded-picture").html(
                            // '<img src="/' + data.path + '" id="picture-' + i + '" width="90" height="68" />'
                        // );
                        $("#removebtn-" + i).attr("status", "0");
                        var fn_orig;
                        if (data.file_orig_name.length > 20) {
                            fn_orig = data.file_orig_name.substr(0, 16) + "...";
                        } else {
                            fn_orig = data.file_orig_name;
                        }
                        $("#uploaded-filename-" + i).html(fn_orig);
                        $("#upload-message").html(data.msg);
                        $("#upload-message").attr("class", "notify");
                        $("#upload-message").show("slow");
                    }
                },
                error: function(data, status, e) {
                    $("#upload-message").html(e);
                    $("#upload-message").attr("class", "fielderror");
                    $("#upload-message").show("slow");
                }
            }
        );
        return false;
    });
}

function upload_image_fieldset_click_callback(id) {
    $("#" + id + "_upload_field").attr("name", "upload");
    $("#" + id + "_upload_id").attr("name", "upload_id");
    $.ajaxFileUpload
    (
        {
            url: '/form/ajax_upload_picture/',
            secureuri: false,
            fileElementId: id + '_upload_field',
            dataType: 'json',
            success: function(data, status) {
                if (typeof(data.error) != 'undefined') {
                    $("#upload-message").html(data.error);
                    $("#upload-message").attr("class", "fielderror");
                    $("#upload-message").show("slow");
                } else {
                    $("#" + id + "_upload_field").val("");
                    //alert(data.msg);
                    //alert(data.file_id);
                    //alert(data.path);
                    // $("#picture-" + data.times).attr("src", "");
                    $("#picture-" + data.times).removeAttr("src");
                    $("#picture-" + data.times).attr("src", "/" + data.path);
                    // $("#uploaded-filename-" + data.times).html(data.file_orig_name);
                    var fn_orig;
                    if (data.file_orig_name.length > 20) {
                        fn_orig = data.file_orig_name.substr(0, 16) + "...";
                    } else {
                        fn_orig = data.file_orig_name;
                    }
                    $("#uploaded-filename-" + data.times).html(fn_orig);
                    $("#upload-message").html(data.msg);
                    $("#upload-message").attr("class", "notify");
                    $("#upload-message").show("slow");
                    $("#uploaded-" + data.times).show("slow");
                    var n = parseInt($("#upload_number").val()) + 1;
                    $("#upload_number").val(n);
                }
            },
            error: function(data, status, e) {
                $("#upload-message").html(e);
                $("#upload-message").attr("class", "fielderror");
                $("#upload-message").show("slow");
            }
        }
    );
    return false;
}

/*
 * expose thumbnail
 */
function initialize_expose_thumbnails() {
    $("#bigpic").hide();
    $("#bigpic").click(
        function(evt) {
            var src_array = $(this).attr("src").split("/");
            var vid = src_array[ src_array.length - 2 ];
            // window.open($(this).attr("src"), "expose_bigview",
                // 'left=0,top=0,toolbar=0,scrollbars=1');
            window.open("/offer/expose_pic/" + vid + "/", "expose_bigview",
                'left=0,top=0,toolbar=0,scrollbars=1');
        }
    );
    $(".thumbnails").children("img").each(
        function(n){
            if (n == 0) {
                $("#bigpic").attr("src", $(this).attr("bigsrc"));
                $("#bigpic").show("slow");
            }
            $(this).mouseover(
                function(evt) {
                    $("#bigpic").attr("src", $(this).attr("bigsrc"));
                }
            );
        }
    );
}

function initialize_park_links() {
	$('.park-link').each(function() {
		var id = '#'+$(this).attr('id');
		init_park(id);
	});
}

function init_park(id) {
	var target = $(id);
    var params = target.attr('href').split(',');
    var vid = params[1];
    var on_label = params[4];
    var off_label = params[5];
	try {
    	var v_str = $.cookie("parked_vehicles");
		var vehicles = JSON.parse(v_str);
		if (typeof vehicles != 'object' || !vehicles) {
			vehicles = [];
		}
	} catch(e) {
		var vehicles = [];
	}
	target.click(toggle_park);
	if (vehicles.contains(vid)) {
		target.text(off_label);
	} else {
		target.text(on_label);
	}
	target.ajaxSuccess(function(){ setTimeout('init_park("'+id+'")', 1500); });
}

function toggle_park() {
	var target = $(this)
    var params = target.attr('href').split(',');
    var vid = params[1];
	var currency = params[2];
	var price = params[3];
    var on_label = params[4];
    var off_label = params[5];
    var v_str = $.cookie("parked_vehicles");
	try {
		var vehicles = JSON.parse(v_str);
		if (typeof vehicles != 'object' || !vehicles) {
			vehicles = [];
		}
	} catch(e) {
		var vehicles = [];
	}
	if (vehicles.contains(vid)) {
//        delete vehicles[vid];
//        $.cookie("parkte_vehicles", JSON.stringify(vehicles), { expires: 365, path: '/' });
//        $(this).text(on_label);
		// direct refresh page if needed
		$.get('/ajaxsrv/delete_park/'+vid+'/', function(data) {
			if (target.attr('rel') == 'refresh') {
				window.location.reload(true);
			} else {
				target.html(data);
			}
		});
	} else {
//        var now = new Date();
//        vehicles[vid] = [currency, price, now.getTime()]
//        $.cookie("parkte_vehicles", JSON.stringify(vehicles), { expires: 365, path: '/' });
//        $(this).text(off_label);
		$.get('/ajaxsrv/add_park/'+vid+'/', function(data) {
			target.html(data);
		});
	}
	return false;
}

/*
 * language selector 
 */
function initialize_language_selector() {
        $("#lang-selector").children("img").each(
            function(n) {
                $(this).click(
                    //some process
                    function(evt) {
                        var l = $.cookie('sitelang');
                        if (l != $(this).attr("lang")) {
                            // $.cookie('sitelang', '', { expires: -1 });
                            $.cookie('sitelang', $(this).attr("lang"), { expires: 365, path: '/' });
                            window.location.reload(true);
                        }
                        return false;
                    }
                );
            }
        );
        // $("img[lang='" + $.cookie("sitelang") + "']").hide();
}

/*
 * set checkpoint in order to be redirect back
 */
function check_if_checkpoint_set () {
    var url = window.location;
    if ($.cookie("checkpoints") == null &&
        window.location.pathname.search("offer") != -1 &&
        window.location.pathname.search("expose") != -1) {
        //console.log(url.protocol + url.host);
        return url.protocol + "//" + url.host + "/";
    } else if ($.cookie("checkpoints") == null &&
        window.location.pathname.search("homepage") != -1 &&
        window.location.pathname.search("expose") != -1) {
        final_url = url.protocol + "//" + url.host +
               "/homepage/" + url.pathname.split("/")[2] + "/";
        //console.log(final_url);
        return final_url
    } else {
        return url.toString();
    }
}

function set_checkpoint() {
	if (!window.name) {
		window.name = Math.random().toString();
	}
	var key = window.name
	try {
		var cps = JSON.parse($.cookie("checkpoints"));
		if (typeof cps != 'object' || !cps) {
			cps = {};
		}
	} catch(e) {
		var cps = {};
	}
    //var cp_url = window.location.toString();
    var cp_url = check_if_checkpoint_set();
    // cookie cps shall be null, and has offer, expose in url
    // has homepage, expose
    //console.log(cp_url);
	cps[key] = cp_url;
    //console.log(cps);
	$.cookie("checkpoints", JSON.stringify(cps), { path: '/' })
	return true;
}

/*
 * redirect to checkpoint
 */
function redirect_to_checkpoint() {
	var key = window.name
	try {
		var cps = JSON.parse($.cookie("checkpoints"));
		if (typeof cps != 'object' || !cps) {
			cps = {};
		}
	} catch(e) {
		var cps = {};
	}
	if (typeof cps == 'object' && cps && key in cps) {
		window.location = cps[key];
		return false;
	}
	return true;
}

/*
give the login dealer a default checkpoint
*/
function set_dealer_checkpoint() {
	if (!window.name) {
		window.name = Math.random().toString();
	}
	var key = window.name
    var cps = {};
	cps[key] = window.location.href + "vehicles/";
	$.cookie("checkpoints", JSON.stringify(cps), { path: '/' })
	return true;
}

/*
dealer logout shall remove checkpoint cookie
*/
function remove_checkpoint() {
    $.cookie("checkpoints", null, {path: '/'})
}

function init_park_details() {
	var timeRE = /%\(datetime\)s/;
	var priceRE = /%\(price\)s/;
	$.get('/ajaxsrv/parkdetails/'+$('#parked-vids').text()+'/',
		function(data) {
			var parkeds = JSON.parse(data);
			if (typeof parkeds != 'object' || !parkeds) {
				parkeds = {};
			}
			for ( v in parkeds ) {
				var text = $('#park-details-'+v).text().replace(priceRE, parkeds[v][0]).replace(timeRE, parkeds[v][1]);
				$('#park-details-'+v).text(text).show();
			}
		}
	);
}

function init_no_printing() {
	$('.no-printing').remove();
	$('#print-bar').appendTo('#content-container');
}

/** EOF
 *  vim:smarttab:ts=4:sw=4:ai:
 */

