var checkBoxesError = false;

var zipPart1cache = null;
var zipPart2cache = null;
var carSelection = new Selection();

function refreshButtons() {
    $(".disabledButton").removeClass("disabledButton");
    $(".disabledCarImage").removeClass("disabledCarImage");
    multipleSubmit.disableButtons();
}

/*
Class for operating with multiple submit cars and their cookies
*/
var multipleSubmit  = {
    cookieName : "multipleSubmit",
    previouslySubmittedCookieName : "multipleSubmitPreviouslySubmitted",
    previouslySubmittedCookieExpiration : 36500,
    contextPath : "/",
    selection : null,
    previouslySubmitted : null,
    multipleSubmitWindow: null,

    initialize : function(carsLimit, limitationError, truncationError, contextPath) {
        this.selection = new Selection();
        this.previouslySubmitted = new Selection();
        this.selection.initialize(carsLimit, limitationError, truncationError);
        this.previouslySubmitted.initialize(0 , "", "");
        this.contextPath = contextPath;
        this.selection.restoreFromCookies(this.cookieName);
        this.previouslySubmitted.restoreFromCookies(this.previouslySubmittedCookieName);
        $(document).ready(function(){
            multipleSubmit.disableButtons();
        });
    },

    chooseCar : function (car, stayOnCarsList) {
        var result = false;
        this.selection.restoreFromCookies(this.cookieName);
        if(this.selection.addToSelection(car, stayOnCarsList)) {
            this.selection.storeInCookies(this.cookieName);
            result = true;
        }
        this.switchButton(false, car);
        statistic.registerCarClicks(2, car);
        if(! stayOnCarsList) {
            this.openMultipleSubmitWindow(car);
        }

        return result;
    },

    chooseCars : function (cars) {
        this.selection.restoreFromCookies(this.cookieName);
        var addedCars = this.selection.addArrayToSelection(cars, false);
        this.selection.storeInCookies(this.cookieName);

        if(addedCars.length != 0) {
            for(var i in addedCars) {
                this.switchButton(false, addedCars[i]);
                statistic.registerCarClicks(2, addedCars[i]);
            }
        }
        $.cookie("tabToShow", "tabContent1", {path: "/"});
        this.openMultipleSubmitWindow(addedCars.join(","));
        return addedCars;
    },

    removeCar : function (car) {
        this.selection.restoreFromCookies(this.cookieName);
        this.selection.deleteFromSelection(car);
        this.selection.storeInCookies(this.cookieName);
        this.removeCarCookies(car);
        location.reload(true);
    },

    removeCarByIndex : function (carIndex) {
        this.selection.restoreFromCookies(this.cookieName);
        var car = this.selection.getSelectionList()[carIndex];
        this.removeCar(car);
        if(window.opener) {
            window.opener.refreshButtons();
        }
    },

    moveCar : function(carIndex, direction) {
        this.selection.restoreFromCookies(this.cookieName);
        var car = this.selection.getSelectionList()[carIndex];
        this.selection.switchSelectionItems(car, direction);
        this.selection.storeInCookies(this.cookieName);
        var destIndex = carIndex + direction
        for(var n = 0; n < 3; n++) {
            var e0 = $('.car_' + n + '_' + carIndex)
            var e1 = $('.car_' + n + '_' + destIndex)
            for(var i = 0; i < e0.length; i++) {
                var tmpValues = new Array();
                $([e0, e1]).each(function(i0){
                    $(this[i]).find('input').each(function(i1){
                        if (this.type == 'checkbox') {
                            tmpValues[tmpValues.length] = new Array(this.id, $(this).attr('checked'), true);
                        } else {
                            tmpValues[tmpValues.length] = new Array(this.id, $(this).val(), false);
                        }
                    });
                    $(this[i]).find('textarea').each(function(i1){
                        tmpValues[tmpValues.length] = new Array(this.id, $(this).val(), false);
                    });
                });
                var tmpHtml = $(e1[i]).html();
                $(e1[i]).html($(e0[i]).html());
                $(e0[i]).html(tmpHtml);
                //store values
                $(tmpValues).each(function(i0){
                    if (this[2]) {
                        $('#'+this[0]).attr('checked', this[1])
                    } else {
                        $('#'+this[0]).val(this[1]);
                    }
                });

            }
        }
//        location.reload(true);
    },

    removeCarCookies : function (car) {
        $.cookie("tmp_mailTextForCar_" + car, null , {path: "/"});
        $.cookie("tmp_mailForm_cb0_" + car, null , {path: "/"});
        $.cookie("tmp_mailForm_cb1_" + car, null , {path: "/"});
        $.cookie("tmp_mailForm_cb2_" + car, null , {path: "/"});
        $.cookie("tmp_mailForm_cb3_" + car, null , {path: "/"});
        $.cookie("tmp_mailForm_cb4_" + car, null , {path: "/"});
        $.cookie("tmp_mailForm_cb5_" + car, null , {path: "/"});
    },

    openMultipleSubmitWindow : function(parameter) {
        this.multipleSubmitWindow = window.open(this.contextPath + "/multipleSubmit/show.htm?addCar=" + parameter,
                "multipleSubmitWindow", "scrollbars=1,resizable=yes,status=yes,toolbar=yes,location=yes,menubar=yes,fullscreen");
        if (this.multipleSubmitWindow !== null) {
            this.multipleSubmitWindow.focus();
            if($.browser.msie && $.browser.version >= 8) {
                $(this.multipleSubmitWindow).focus();
            }
            if(! this.multipleSubmitWindow.opener) {
                this.multipleSubmitWindow.opener = window;
            }
        }
    },



    reset : function(){
        this.selection.resetSelection();
        //remove from cookies
        this.selection.storeInCookies(this.cookieName);
    },

    switchButton : function(enableButton, carId) {
        if(enableButton) {
            $(".jsSubmitButton_" + carId).removeClass("disabledButton");
            $("#carImg" + carId).removeClass("disabledCarImage");
        }
        else{
            $(".jsSubmitButton_" + carId).addClass("disabledButton");
            $("#carImg" + carId).addClass("disabledCarImage");

        }
    },

    disableButtons : function() {
        var cars;
        var i;
        this.selection.restoreFromCookies(this.cookieName);
        this.previouslySubmitted.restoreFromCookies(this.previouslySubmittedCookieName);

        if(! this.selection.isEmpty()) {
            cars = this.selection.getSelectionList();
            for(i in cars) {
                this.switchButton(false, cars[i]);
            }
        }
        if(! this.previouslySubmitted.isEmpty()) {
            cars = this.previouslySubmitted.getSelectionList();
            for(i in cars) {
                this.switchButton(false, cars[i]);
            }
        }
    },

    appendPreviouslySubmittedCars : function(){
        this.previouslySubmitted.addArrayToSelection(this.selection.getSelectionList(), true);
        this.previouslySubmitted.storeInCookies(this.previouslySubmittedCookieName, this.previouslySubmittedCookieExpiration);
    }
}


//COMMON METHODS FOR MULTIPLE SUBMIT PAGE (related to UI, validation etc)


function changeActiveStep(currentStep, nextStep) {
    $("#step" + currentStep).removeClass("step" + currentStep + "Active");
    $("#step" + nextStep).addClass("step" + nextStep + "Active");
}

function clearDefaultComments() {
    $("textarea").each(function() {
        if ($(this).val() == messages["default_mail_comment"]) {
            $(this).val("");
        }
    });
}

function beforeSubmit() {
    if(! validateFields()) {
        return false;
    }
    clearDefaultComments();
    clearTemporaryValues();
    multipleSubmit.appendPreviouslySubmittedCars();
    $("#multipleSubmitForm").trigger("submit");
    return true;
}

function showTab(tabControl, tabToShow, tabToHide, tabToHide0, isSingleMail) {
    $(".tabControls div").removeClass("active");
    $("#" + tabControl).addClass("active");
    $("#" + tabToHide).hide();
    $("#" + tabToHide0).hide();
    $("#" + tabToShow).show();
    $("#isSingleMail").val(isSingleMail);
    $.cookie("tabToShow", tabToShow, {path: "/"});
}

var messages = new Array();

function formatDigitValue(object) {
    object.value = object.value.replace(/[^\d]/g, "");
}


function validateLength(field, length, nextFieldId) {
    if(field.value.length > length)
        field.value = field.value.substring(0, length - 1);
    if(field.value.length == length && nextFieldId != '') {
        $(document.getElementById(nextFieldId)).focus();
    }
}

function validateFields() {
    if(multipleSubmit.selection.getSelectionCount() == 0) {
        alert(messages["multipleSubmit_noCarsSelected"]);
        return false;
    }
    var result = '';
    var isSingleMail = document.getElementById("isSingleMail").value;
    var formIndex = (isSingleMail == "true") ? 1 : 2;
    var phoneCodeError = validatePhoneCode(formIndex);
    result += validateName(formIndex) +
              validatePrefecture(formIndex) +
              validateEmail(formIndex) +
              validateEmailComfirmation(formIndex) +
              validateCheckboxes(formIndex, phoneCodeError.length > 0) +
              phoneCodeError;
    if(result != "") {
        alert(result);
        return false;
    }
    return true;
}

function simpleValidateFields() {
    var result = '';
    var formIndex = 1;
    result += validateName(formIndex) +
              validatePrefecture(formIndex) +
              validateEmail(formIndex) +
              validateEmailComfirmation(formIndex) +
              validateCheckboxes(formIndex, false) +
              validatePhoneCode(formIndex);
    if(result != "") {
        alert(result);
        return false;
    }
    return true;
}

function setError(object) {
    $(object).parent().removeClass("field");
    $(object).parent().addClass("errorField");
}

function unsetError(object) {
    $(object).parent().removeClass("errorField");
    $(object).parent().addClass("field");
}

function validateName(formIndex) {
    var userName = $(".userForm input[name='userName" + formIndex + "']");
    var userSurname = $(".userForm input[name='userSurname" + formIndex + "']");
    var userNameVal = userName.val() + userSurname.val();
    if(userNameVal == "" ) {
        setError(userName);
        setError(userSurname);
        return "- " + messages["multipleSubmit_userName_empty"] + "\n";
    } else {
        var nameLength = userNameVal.length;
        for (var i = 0; i < nameLength - 2; i++) {

            if (userNameVal.charAt(i) == userNameVal.charAt(i + 1) && userNameVal.charAt(i + 1) == userNameVal.charAt(i + 2)) {
                setError(userName);
                setError(userSurname);
                return "- " + messages["multipleSubmit_threeEqualSymbolsNotAllowed"] + "\n";
            }
        }

    }

    unsetError(userName);
    unsetError(userSurname);
    return "";
}

function validatePrefecture(formIndex) {
    var prefecture = $(".userForm select[name='prefectureId" + formIndex + "']");
    if(prefecture.val() == -1){
        setError(prefecture);
        return "- " + messages["multipleSubmit_prefecture_empty"] + "\n";
    }
    unsetError(prefecture);
    return "";
}

function validateEmail(formIndex) {
    var email = $(".userForm input[name='email" + formIndex + "']");
    if(email.val() == "") {
        setError(email);
        return "- " + messages["multipleSubmit_email_empty"] + "\n";
    }
    var emailRegexp = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!emailRegexp.test(email.val())) {
        setError(email);
        return "- " + messages["multipleSubmit_email_format"] + "\n";
    }
    unsetError(email);
    return "";
}

function validateEmailComfirmation(formIndex) {
    var email = $(".userForm input[name='email" + formIndex + "']");
    var emailConfirmation = $(".userForm input[name='emailConfirmation" + formIndex + "']");
    if(emailConfirmation.val() == "" || email.val() != emailConfirmation.val()) {
        setError(emailConfirmation);
        return "- " + messages["multipleSubmit_email_notConfirmed"] + "\n";
    }
    unsetError(emailConfirmation);
    return "";
}

function validateCheckboxes(formIndex, phoneValidationFailed) {
    var result = "";

    var carFailedIds = [];
    var carIds = [];
    var globalCheckBoxesError = false;
    var globalCommentError = false;

    $(".cbx" + formIndex).each(function(){
        var checkBoxesError = false;
        var commentError = false;
        var id = this.id;
        var checkedCheckBoxes = $(this).find("input[type=checkbox]:checked").length;

        if(checkedCheckBoxes == 0) {
            checkBoxesError = true;
            globalCheckBoxesError = true;

        } else if (checkedCheckBoxes == 1) {
            var commentIsRequired;
            var inputText;
            if (formIndex == 1) {
                commentIsRequired = $("#cb5_ss").get(0);
            } else {
                commentIsRequired = $(this).find("input[name^='mailForm_cb5_']").get(0);
            }
            if ((commentIsRequired.checked == "true" || commentIsRequired.checked == true)) {
                if (formIndex == 1) {
                    inputText = $("#singleMailText").val();
                } else {
                    var carId = commentIsRequired.name.substring("mailForm_cb5_".length);
                    inputText = $("#mailTextForCar_" + carId).val();
                }

                if (inputText == "" || inputText == messages["default_mail_comment"]) {
                    commentError = true;
                    globalCommentError = true;
                }

            }

        }

        if (formIndex == 2 && (commentError || checkBoxesError)) {
                carFailedIds.push(id.substring(27, id.length));
            } else {
                carIds.push(id.substring(27, id.length))
            }



    });





    if(globalCheckBoxesError) {
        result = result + "- " + messages["multipleSubmit_checkboxNotChecked"] + "\n";
        if (formIndex == 2) {
            result = result + "  " + messages["multipleSubmit_orangeSelectionText"] + "\n";
        }
    }

    if(globalCommentError) {
        result = result = "- " + messages["multipleSubmit_noCommentEntered"] + "\n";
    }

    if (formIndex == 2) {
        selectGulliverCarsOnPage(carIds, carFailedIds, phoneValidationFailed);
    }

    return result;

}

function validatePhoneCode(formIndex) {

    var phoneCode1 = $(".userForm input[name='phone" + formIndex + "_1']");
    var phoneCode2 = $(".userForm input[name='phone" + formIndex + "_2']");
    var phoneCode3 = $(".userForm input[name='phone" + formIndex + "_3']");
    if (prefecturePhoneCodes != undefined) {

        var phoneCodeVal = phoneCode1.val() + phoneCode2.val() + phoneCode3.val();
        if(phoneCodeVal == "") {
            setError(phoneCode1);
            setError(phoneCode2);
            setError(phoneCode3);
            selectGulliverCarsPhoneOnPage(formIndex, true);
            return "- " + messages["multipleSubmit_phone_empty"] + "\n";
        } else {

            var prefecture = $(".userForm select[name='prefectureId" + formIndex + "']");
            if(prefecture.val() != -1){

                if (!isPhoneCodeMatchPrefecture(phoneCodeVal, prefecture.val())) {
                    setError(phoneCode1);
                    setError(phoneCode2);
                    setError(phoneCode3);
                    selectGulliverCarsPhoneOnPage(formIndex, true);
                    return "- " + messages["multipleSubmit_phone_notMatchPref"] + "\n";
                }
            }
        }
    }

    selectGulliverCarsPhoneOnPage(formIndex, false);

    unsetError(phoneCode1);
    unsetError(phoneCode2);
    unsetError(phoneCode3);

    return "";
}


function selectGulliverCarsPhoneOnPage(formIndex, select) {

     if (select == true) {
         if (formIndex == 1) {
             performSelection("td[id^='leftCorner_ss_glv']", "leftCorner", "leftCornergulliver");
             performSelection("td[id^='middle_ss_glv']", "middle", "middlegulliver");
             performSelection("td[id^='rightCorner_ss_glv']", "rightCorner", "rightCornergulliver");
         } else {
             performSelection("td[id^='title_ms_glv']", "title", "titlegulliver");
             performSelection("td[id^='rightCorner_ms_glv']", "rightCorner", "rightCornergulliver");
             performSelection("div[id^='carTitle_ms_glv']", "carTitle", "carTitlegulliver");
             performSelection("div[id^='rightTitleBorder_ms_glv']", "rightTitleBorder", "rightTitleBordergulliver");
         }
     } else {
         if (formIndex == 1) {
             performSelection("td[id^='leftCorner_ss_glv']", "leftCornergulliver", "leftCorner");
             performSelection("td[id^='middle_ss_glv']", "middlegulliver", "middle");
             performSelection("td[id^='rightCorner_ss_glv']", "rightCornergulliver", "rightCorner");
         } else {
             performSelection("td[id^='title_ms_glv']", "titlegulliver", "title");
             performSelection("td[id^='rightCorner_ms_glv']", "rightCornergulliver", "rightCorner");
             performSelection("div[id^='carTitle_ms_glv']", "carTitlegulliver", "carTitle");
             performSelection("div[id^='rightTitleBorder_ms_glv']", "rightTitleBordergulliver", "rightTitleBorder");
         }
     }
}

function selectGulliverCarsOnPage(carIds, carFailedIds, phoneValidationFailed) {

     for (var i = 0; i < carFailedIds.length; i++) {
         if (!phoneValidationFailed) {
             performSelection("td[id^='title_ms_glv" + carFailedIds[i] + "']", "title", "titlegulliver");
             performSelection("td[id^='rightCorner_ms_glv" + carFailedIds[i] + "']", "rightCorner", "rightCornergulliver");
             performSelection("div[id^='carTitle_ms_glv" + carFailedIds[i] + "']", "carTitle", "carTitlegulliver");
             performSelection("div[id^='rightTitleBorder_ms_glv" + carFailedIds[i] + "']", "rightTitleBorder", "rightTitleBordergulliver");
         }
         performSelection("td[id^='title_ms_" + carFailedIds[i] + "']", "title", "titlegulliver");
         performSelection("td[id^='rightCorner_ms_" + carFailedIds[i] + "']", "rightCorner", "rightCornergulliver");
         performSelection("div[id^='carTitle_ms_" + carFailedIds[i] + "']", "carTitle", "carTitlegulliver");
         performSelection("div[id^='rightTitleBorder_ms_" + carFailedIds[i] + "']", "rightTitleBorder", "rightTitleBordergulliver");
     }

    for (var i = 0; i < carIds.length; i++) {
         if (!phoneValidationFailed) {
             performSelection("td[id^='title_ms_glv" + carIds[i] + "']", "titlegulliver", "title");
             performSelection("td[id^='rightCorner_ms_glv" + carIds[i] + "']", "rightCornergulliver", "rightCorner");
             performSelection("div[id^='carTitle_ms_glv" + carIds[i] + "']", "carTitlegulliver", "carTitle");
             performSelection("div[id^='rightTitleBorder_ms_glv" + carIds[i] + "']", "rightTitleBordergulliver", "rightTitleBorder");
         }
         performSelection("td[id^='title_ms_" + carIds[i] + "']", "titlegulliver", "title");
         performSelection("td[id^='rightCorner_ms_" + carIds[i] + "']", "rightCornergulliver", "rightCorner");
         performSelection("div[id^='carTitle_ms_" + carIds[i] + "']", "carTitlegulliver", "carTitle");
         performSelection("div[id^='rightTitleBorder_ms_" + carIds[i] + "']", "rightTitleBordergulliver", "rightTitleBorder");
     }


}


function performSelection(query, rmClass, addClass) {
    $(query).each(function(){
        $(this).removeClass(rmClass);
        $(this).addClass(addClass);
    });
}


function isPhoneCodeMatchPrefecture(phoneCode, prefCode) {

    if (prefecturePhoneCodes != null && prefecturePhoneCodes != undefined) {
        var exceptionalPhoneCodes = prefecturePhoneCodes["null"];
        if (exceptionalPhoneCodes != null && exceptionalPhoneCodes != undefined) {
            var exceptionalCodesSize = exceptionalPhoneCodes.length;
            for (var i = 0; i < exceptionalCodesSize; i++) {
                var codeLen = exceptionalPhoneCodes[i].length;
                if (phoneCode.substring(0, codeLen) == exceptionalPhoneCodes[i]) {
                    return true;
                }
            }
        }

        var phoneCodes = prefecturePhoneCodes[prefCode];
        if (phoneCodes != null && phoneCodes != undefined) {
            var phoneCodesSize = phoneCodes.length;
            for (var i = 0; i < phoneCodesSize; i++) {
                var codeLen = phoneCodes[i].length;
                if (phoneCode.substring(0, codeLen) == phoneCodes[i]) {
                    return true;
                }
            }
        }
    }

    return false;
}

function clearTemporaryValues() {
    $(".tabContent textarea, .tabContent input[type='text'], .tabContent input[type='checkbox'], .tabContent select").each(function(){
        $.cookie("tmp_" + $(this).attr("name"), null, {path: "/"});
    });
}

function storeTemporaryValue(field) {
    var valueToStore = "";
    if($(field).attr("tagName").toLowerCase() == "input"
            && $(field).attr("type").toLowerCase() == "checkbox") {
        valueToStore = ($(field).attr("checked") == null || $(field).attr("checked") == undefined || !$(field).attr("checked")) ? false : "checked";
    }
    else {
        valueToStore = $(field).val();
    }
    $.cookie("tmp_" + $(field).attr("name"), valueToStore, {path: "/"});
}

$(document).ready(function(){
    //restoring temporary inputs values from cookies (to persist user input when refreshing the page)
    $(".tabContent textarea, .tabContent input[type='text'], .tabContent select").each(function(){
        var text = $.cookie("tmp_" + $(this).attr("name"));
        if(text != null && text != undefined) {
            $(this).val(text);
        }
    });

    $(".tabContent input[type='checkbox']").each(function(){
        var text = $.cookie("tmp_" + $(this).attr("name"));
        if(text != null && text != undefined ) {
            if(text == "checked")
                $(this).attr("checked", "checked");
            else
                $(this).removeAttr("checked");
        }
    });

    $(".tabContent textarea, .tabContent input[type='text'], .tabContent select").blur(function(){
        storeTemporaryValue(this);
    });

    $(".tabContent input[type='checkbox']").change(function(){
        storeTemporaryValue(this);
    });

    $('#submitButton').hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });
});

function commentFieldInitialization(id) {
    var commentField = $("#" + id);
    if (commentField.val() == messages["default_mail_comment"]) {
        commentField.val("");
    }
}

function clickSubmitButton() {
    $("#submitButton").trigger("click");
}

function formatDigitValue(object) {
    object.value = object.value.replace(/[^\d]/g, "");
}

function validateLength(field, length, nextFieldId) {
    var value = field.value;
    if(value.length > length) {
        field.value = value.substring(0, length - 1);
    } else if(value.length == length && nextFieldId != '') {
        $('#' + nextFieldId).focus();
    }
}

function checkInputZip(zipPart1, zipPart2, cp, prefectureId, addrId, linksPopUpId) {
    var zipPart1Val = $('#' + zipPart1).val();
    var zipPart2Val = $('#' + zipPart2).val();


    if ((zipPart1cache != zipPart1Val || zipPart2cache != zipPart2Val) &&
        zipPart1Val.length == 3 && zipPart2Val.length == 4) {


        $.ajax({
            type: "GET",
            url: cp + "/ajax/cityzip.htm",
            data: { zipPart1: zipPart1Val, zipPart2: zipPart2Val },
            dataType: 'JSON',

            success: function(resp) {
                if (resp == null || resp == undefined || resp.length == 0) {
                    $('#' + prefectureId).val('-1');
                    $('#' + addrId).val('');
                } else {
                    var data = eval(resp);
                    if (data.length == 1) {
                        $('#' + prefectureId).val(data[0]['city']['prefecture']['id']);
                        $('#' + addrId).val(data[0]['city']['name'] + data[0]['citySide']);
                    } else if (data.length > 1) {

                        var topElement = $('#' + linksPopUpId + ' span[name=links]');

                        var documentFragment = document.createDocumentFragment();

                        var zipSpan = document.createElement('span');
                        zipSpan.appendChild(document.createTextNode(zipPart1Val + '-' + zipPart2Val));
                        documentFragment.appendChild(zipSpan);

                        var prefDiv = document.createElement('div');
                        prefDiv.appendChild(document.createTextNode(data[0]['city']['prefecture']['name']));
                        documentFragment.appendChild(prefDiv);

                        documentFragment.appendChild(document.createElement('br'));

                        var elemCount = data.length;
                        for (var i = 0; i < elemCount; i++) {
                            var addr = data[i]['city']['name'] + data[i]['citySide'];
                            var div = document.createElement('div');
                            var a = document.createElement('a')
                            a.href = 'javascript:selectCityZip(\'' + prefectureId + '\', \'' + data[i]['city']['prefecture']['id'] + '\', \'' + addrId + '\',\'' + addr + '\', \'' + linksPopUpId + '\');';
                            a.appendChild(document.createTextNode(addr));
                            div.appendChild(a);
                            documentFragment.appendChild(div);
                        }

                        var links = $('#' + linksPopUpId + ' span[name=links] > *').remove();
                        topElement.append(documentFragment);
                        $('#' + linksPopUpId).show();

                    }
                }
            }

        });
    }

    zipPart1cache = zipPart1Val;
    zipPart2cache = zipPart2Val;
}



function toogleGroup(group) {
    if($(group).hasClass("collapsedGroup")) {
        $("." + group.id).show();
        $(group).removeClass("collapsedGroup");
    }
    else {
        $("." + group.id).hide();
        $(group).addClass("collapsedGroup");
    }
}

function selectCityZip(prefectureId, prefectureChoise, addrId, addrChoise, linksPopUpId) {
     $('#' + linksPopUpId).hide();
     $('#' + prefectureId).val(prefectureChoise);
     $('#' + addrId).val(addrChoise);
}

function commonRemoveCarByIndex(carIndex) {
    var car = multipleSubmit.selection.getSelectionList()[carIndex];
    carSelection.deleteFromSelection(car);
    carSelection.storeInCookies("car");
    multipleSubmit.removeCarByIndex(carIndex);
}





