function submitLang(lang) {
    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.elements["lang"].value = lang;
        form.elements["method"].value = "lang";
        form.submit();
        return false;
    }
    return false;
}
function submitMain(startSearch) {
    var form = document.getElementById("htmlSearchForm");
    if (form && checkInputValues()) {
        form.elements['startSearch'].value = startSearch;
        form.elements["method"].value = "search";
        form.submit();
        return false;
    }
    return false;
}

function forceRefresh() {
    var selectBoxes = new Array();
    selectBoxes[0] = document.getElementById("manufacturer");
    selectBoxes[1] = document.getElementsByName("priceFrom")[0];
    selectBoxes[2] = document.getElementsByName("priceTo")[0];
    selectBoxes[3] = document.getElementsByName("mileageFrom")[0];
    selectBoxes[4] = document.getElementsByName("mileageTo")[0];
    selectBoxes[5] = document.getElementsByName("yearFrom")[0];
    selectBoxes[6] = document.getElementsByName("yearTo")[0];
    selectBoxes[7] = document.getElementsByName("prefectureId")[0];

    for (var i in selectBoxes) {
        if(selectBoxes[i] != null)
            selectBoxes[i].options[0].selected = "selected";
    }

    var bodyIds = document.getElementsByName("bodyId");
    if(bodyIds[0].nodeName.toLowerCase() == "select") {
        bodyIds[0].options[0].selected = "selected";
    }
    else {
        for (var i in bodyIds)
            bodyIds[i].checked = "";
    }

    var keywords = document.getElementsByName("keywords")[1];
    if(keywords != null)
        keywords.value = "";
}

function resetMain(){
    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.reset();
        forceRefresh();
    }
    return false;
}
function delHistory(id) {
        var form = document.getElementById("htmlSearchForm");
        if (form) {
            form.elements["method"].value = "delHistory";
            form.elements["historyId"].value = id;
            form.submit();
            return false;
        }
    return false;
}
function runHistory(id) {
    var form = document.getElementById("htmlSearchForm");
    if (form) {
        form.elements["method"].value = "runHistory";
        form.elements["historyId"].value = id;
        form.submit();
        return false;
    }
    return false;
}
function show(id) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.style.display = 'block';
        obj.myVis = true;
    }
}
function show2(id) {
    var obj = document.getElementById(id);
    var main = document.getElementById("historyList");
    var pan = document.getElementById("panel");
    if (main && obj && pan) {
        pan.innerHTML = obj.innerHTML;
        show("panel");
        pan.style.left = main.offsetLeft - pan.offsetWidth - 5;
        pan.style.top = main.offsetTop;
    }
}
function hide(id) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.myVis = false;
        obj.style.display = 'none';
    }
}
function hideD(id) {
    var obj = document.getElementById(id);
    if (obj) {
        obj.myVis = false;
        setTimeout("hideMyVis('" + id + "')", 500);
    }
}
function hideMyVis(id) {
    var obj = document.getElementById(id);
    if (obj && obj.myVis != true) {
        obj.myVis = false;
        hide(id);
    }
}
function bgC(obj, color) {
    obj.style.backgroundColor = color;
}
function changeManufacturer() {
    var objMan = document.getElementById("manufacturer");
    var objMod = document.getElementById("model");
    if (objMan && objMod) {
        objMod.innerHTML = '';
        objMod.options[0] = new Option('全モデル', 0);
        var ik = objMod.length;
        var manId = objMan[objMan.selectedIndex].value;
        
        // first go through models without group
        for (var i = 0; models && i < models.length; i++) {
            if (manId == models[i].manId) {
                objMod.options[ik] = new Option(models[i].name, models[i].id);
                objMod.options[ik].bodyId = models[i].bodyId;
                ik++;
            }
        }
        
        // then we go through the groups
        for (var i = 0; modelGroups && i < modelGroups.length; i++) {
        	if (manId == modelGroups[i].manId && modelGroups[i].models.length > 0) {
        		// first we add group itself
        		var og = document.createElement('optgroup');
        		og.label = modelGroups[i].name;
        		objMod.appendChild(og);
        		
        		// then the models from this group
        		for (var j = 0; modelGroups[i].models && j < modelGroups[i].models.length; j++) {
        			var op = document.createElement('option');
        			og.appendChild(op);
        			op.value = modelGroups[i].models[j].id;
        			op.innerHTML = modelGroups[i].models[j].name;
        			op.bodyId = modelGroups[i].models[j].bodyId;
        		}
        	}
        }
        
        if (objMod.onchange) {
            objMod.onchange();
        }
    }
}
var modelGroups = new Array();

function ModelGroup(id, name, manId, models) {
	this.id = id;
	this.name = name;
	this.manId = manId;
	this.models = models;
	return this;
}

function changeModel() {
    var objMod = document.getElementById("model");
    var objMod2 = document.getElementById("model2");
    if (objMod && objMod2) {
        objMod2.length = 1;
	        var ik = 1;
	        var modelId = objMod[objMod.selectedIndex].value;
	        for (var i = 0; models2 && i < models2.length; i++) {
	            if (modelId == models2[i].modelId) {
	                objMod2.options[ik] = new Option(models2[i].name, models2[i].id);
	                ik++;
	            }
	        }
    	}
    }
var models = new Array();
var models2 = new Array();
function Model(id, name, manId, bodyId) {
    this.id = id;
    this.name = name;
    this.manId = manId;
    this.bodyId = bodyId;
    return this;
}
function Model2(id, name, modelId, bodyId) {
    this.id = id;
    this.name = name;
    this.modelId = modelId;
    this.bodyId = bodyId;
    return this;
}
function initLists(model, model2) {
    var objMan = document.getElementById("manufacturer");
    var objMod = document.getElementById("model");
    var objMod2 = document.getElementById("model2");
    if (objMan && objMod && objMod2) {
        changeManufacturer();
        GUI.setSelectedIndex(objMod, model);
        changeModel();
        GUI.setSelectedIndex(objMod2, model2);
    }
}
function carResize(data) {
    try {
        for (var i1 = 0; i1 < data.length; i1++) {
            var maxHeight = 0;
            for (var i2 = 0; i2 < data[i1].length; i2++) {
                var table = document.getElementById("c" + data[i1][i2]);
                maxHeight = Math.max(maxHeight, table.clientHeight);
            }
            for (var i2 = 0; i2 < data[i1].length; i2++) {
                var table = document.getElementById("c" + data[i1][i2]);
                table.style.height = maxHeight;
            }
        }
    } catch (err) {
    }
}
function setPrefecture(prefId) {
    try {
        var obj = document.getElementById("prefecture");
        if (obj && obj.length) {
            for (var ik = 0; ik < obj.length; ik++) {
                if (prefId == obj[ik].value) {
                    obj[ik].selected = true;
                    break;
                }
            }
        }
    } catch (err) {
        alert(err.description);
    }
}
function carview(path, id, pId, lang) {
    var finalURL = path + '/front.do?method=portalCarView&id='+id;
    if (pId) finalURL += '&pId=' + pId;
    if (lang) finalURL += '&lang=' + lang;
    window.open(finalURL, "","top=100,left=0,width=1000,height=740,scrollbars=1,resizable=yes,status=no,toolbar=no,menubar=no");
    return false;
}
function checkInputValues() {
    var message = "";
    var frm = document.getElementById('htmlSearchForm');
    if (frm) {
        message += checkSelect(frm, 'price', true);
        message += checkSelect(frm, 'mileage', true);
        message += checkSelect(frm, 'year', false);
        if (message.length > 0) {
            alert(message);
            return false;
        }
        return true;
    }
    return false;
}
function checkSelect(frm, name, direction) {
    var elF = frm.elements[name + 'From'];
    var elT = frm.elements[name + 'To'];
    if (elF && elT && elF.selectedIndex > 0 && elT.selectedIndex > 0) {
        if (direction ? elF.selectedIndex > elT.selectedIndex : elF.selectedIndex < elT.selectedIndex) {
            return errors[name + 'Range'] + "\n";
        }
    }
    return "";
}

function sortCars(sortingType, anchor) {
    $('#mainSearchForm form [name="sortForm.sortType"]').val(sortingType);
    if($('#mainSearchForm form [name="sortForm.sortOrder"]').val() == 0) {
        $('#mainSearchForm form [name="sortForm.sortOrder"]').val(1);
    }
    else {
        $('#mainSearchForm form [name="sortForm.sortOrder"]').val(0);
    }
    var action = $('#mainSearchForm form').attr("action");
    var anchorPosition = action.lastIndexOf("#");
    if(anchorPosition != -1) {
        action = action.substring(0, anchorPosition);
    }
    $('#mainSearchForm form').attr("action", action += "#" + anchor);
    submitMainNew(1);
}

function switchColor(node) {
    if($(node).attr("checked")){
        $(node).parent("div").addClass("checkedRow");
    }
    else {
        $(node).parent("div").removeClass("checkedRow");
    }
}

function switchAttributes(condition, pattern, affectChildern, affectParent) {
    if(condition){
        $(pattern).attr("checked","checked");
    }
    else{
        $(pattern).removeAttr("checked");
    }
    if(affectChildern) {
        $(pattern).each(function(){
            switchColor($(this));
        });
    }
    if(affectParent) {
        switchColor($(pattern));
    }
}

function clickDivNode(node) {
    var checkBox = $(node).children("input[type=checkbox]");
    if(checkBox.attr("checked")) {
        checkBox.removeAttr("checked");
    }
    else {
        checkBox.attr("checked", "checked");
    }
    clickCheckboxNode(checkBox);
    return false;
}

function clickCheckboxNode(node) {
    if(node.attr("id") == "area-all") { //root node, check/uncheck all
        switchAll(node);
        switchColor(node);
    }
    else {
        if(node.attr("id").indexOf("area-") != -1 ) {//some area node, check/uncheck parent node and child prefectures
            switchChildren(node);
            switchParent(node);
            switchColor(node);
        }
        else {//some prefecture, check/uncheck parent node
            switchParent(node);
            switchColor(node);
        }
    }
}

function switchAll(mainNode) {
    switchAttributes($(mainNode).attr("checked"),
            "#prefecturesSelection .areasList input[type=checkbox]", true, false);
}

function switchChildren(node) {
    switchAttributes($(node).attr("checked"),
            "#prefecturesSelection .areasList .parent-" + $(node).attr("id"), true, false);
}

function switchParent(node) {
    var parent = $(node).attr("class");
    parent = parent.replace("parent-", "");
    var siblingsCount = $("#prefecturesSelection .areasList .parent-" + parent).length;
    var checkedSiblingsCount = $("#prefecturesSelection .areasList input[class=parent-" + parent + " ]:checked").length;
    switchAttributes(siblingsCount == checkedSiblingsCount,
            "#prefecturesSelection .areasList #" + parent, false, true);
    var allNodesCount = $("#prefecturesSelection .areasList input[type=checkbox]").length;
    var allCheckedNodesCount = $("#prefecturesSelection .areasList input[type=checkbox]:checked").length;
    switchAttributes(allNodesCount == allCheckedNodesCount,
            "#prefecturesSelection #area-all", false, true);
}

function submitMainNew(startSearch) {
    var prefetures = new Array();
    var form = document.getElementById("htmlSearchForm");
    if (form && checkInputValues()) {
        form.elements['startSearch'].value = startSearch;
        form.elements["method"].value = "search";
        if(! $("#prefecturesSelection #area-all").attr("checked")){
            var i = 0;
            var arr = $("#prefecturesSelection input[type=checkbox]:checked");
            $("#prefecturesSelection input[type = checkbox]:checked").each( function(){
                if($(this).attr("class") != "parent-area-all") {
                    prefetures[i] = new Number($(this).val());
                    i++;
                }
            });
            $("#htmlSearchForm input[name='prefectures']").val(prefetures);
        }
        else {
            $("#htmlSearchForm input[name='prefectures']").val("");
        }
        $("#htmlSearchForm").trigger("submit");
    }
    return false;
}

//Very important!!!
//init prefectures selection area
function initPrefecturesSelection() {
    $("#prefecturesSelection input[type=checkbox]").click(function(e) {
        e.stopPropagation();
    });
    var prefectures = $("#mainSearchForm input[name='prefectures']").val();
    if(prefectures && prefectures != "") {
        var ids = prefectures.split(",");
        for(var i in  ids) {
            clickDivNode($("#prefecturesSelection input[type=checkbox][value=" + ids[i] +"]").parent("div"));
        }
    }
    var currentPrefecture = $("#prefecturesSelection .currentPrefecture"); //stores prefect. Id on prefect. pages. like /pref/osaka.html
    if(currentPrefecture.length != 0) {
        clickDivNode($("#prefecturesSelection input[type=checkbox][value=" + currentPrefecture.val() +"]").parent("div"));
    }
}

function switchLayout(oldLayout, pathString) {
    if(oldLayout) {

        $.cookie("isOldLayout", "true",{ path: pathString, expires: 35000 });
    }
    else {
        $.cookie("isOldLayout", null, { path: pathString});
    }
    $("#htmlSearchForm").trigger("submit");
}
