// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

/**
  * helper functions for BOOKFOUNDATION originated page handling
  */

function setFormOfDivDisabled(divid, isDisabled) {
    var d = $(divid);
    var inputs = d.getElementsByTagName("INPUT");
    for (var i = 0; i < inputs.length; i++) {
      inputs[i].disabled = isDisabled;
    }
    var inputs = d.getElementsByTagName("SELECT");
    for (var i = 0; i < inputs.length; i++) {
      inputs[i].disabled = isDisabled;
    }
    var inputs = d.getElementsByTagName("TEXTAREA");
    for (var i = 0; i < inputs.length; i++) {
      inputs[i].disabled = isDisabled;
    }
}

function checkIfChild() {
    if($("currentpage_parent_id").value != "0") {
        $("page_is_child").checked = true;
    } else {
        $("page_is_child").checked = false;
        $("currentpage_parent_id").disabled = true;
    }
}

function changeIfChild() {
    if($("page_is_child").checked) {
        $("currentpage_parent_id").disabled = false;
    } else {
        $("currentpage_parent_id").disabled = true;
        $("currentpage_parent_id").value = "0";
    }
}

/**
  * BOOKFINDER specific functions
  */

var selectfilters = new Array();

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function getNextSelectValue(x) {
    var cont = x.parentNode;
    var i = 0;
    var look = true;
    var v = "";
    while (i < cont.childNodes.length && look) {
        if (cont.childNodes[i]) {
            if (cont.childNodes[i].nodeType == 1) {
                if (cont.childNodes[i].nodeName.toLowerCase() == "select") {
                    v = cont.childNodes[i].value;
                    look = false;
                }
            }
        }
        i++;
    }
    if (!look) {
        if (v != "") { // has selected option
            return v;
        }
    }
    return false;
}

function editPopup(parent, fid, hid) {
    if (getNextSelectValue(parent)) {
        $(hid).value = getNextSelectValue(parent);
        $(fid + "_submit").click();
        showPopup();
    } else {
        //alert("err");
    }
}

function showPopup() {
    var bg = $("blackbg");
    var ps = getPageSize();
    bg.style.display = "block";
    bg.style.width = ps[0] + "px";
    bg.style.height = ps[1] + "px";
    if (is_ie) {
        var selects = document.getElementsByTagName("SELECT");
        for (i = 0; i < selects.length; i++) {
            selects[i].style.display = "none";
        }
    }
    $("layer").style.display = "block";
}

function hidePopup() {
    hideItem("layer");
    hideItem("blackbg");
}

function hideItem(itemid) {
    $(itemid).style.display = "none";
}

function showItem(itemid) {
    $(itemid).style.display = "";
}

function selectDefaultOption(itemid) {
    if ($(itemid).options.length > 0) {
        $(itemid).selectedIndex = 0;
    }
}

function deleteRow(w) {
    var p = w;
    var rowid = -1;
    var look = true;
    while (look) {
        if (p.parentNode) {
            if (p.parentNode.nodeName) {
                if (p.parentNode.nodeName.toLowerCase() == "tr") {
                    rowid = p.parentNode.rowIndex;
                    look = false;
                } else {
                    p = p.parentNode;
                }
            } else {
                p = p.parentNode;
            }
        } else {
            look = false;
        }
    }
    if (rowid > -1) {
        while (p) {
            if (p.parentNode) {
                if (p.parentNode.nodeName) {
                    if (p.parentNode.nodeName.toLowerCase() == "table") {
                        p.parentNode.deleteRow(rowid);
                        p = false;
                    } else {
                        p = p.parentNode;
                    }
                } else {
                    p = p.parentNode;
                }
            } else {
                p = false;
            }
        }
    }
}

/**
  * function addRow
  * add a row to a html table
  * t: String   - id of the table
  * r: String   - array of id's of inputs to get cell data from
  *               (eg.: a select and a text field with some additional info)
  */
function addRow(t, r) {
    if ($(t)) {
        var row = $(t).insertRow(1);
        var cols = r.split(";");
        var cell;
        for (var i = 0; i < cols.length; i++) {
            cell = row.insertCell(i);
            cell.className = "imp";
            if ($(cols[i]).options) {
                cell.innerHTML = $(cols[i]).options[$(cols[i]).selectedIndex].innerHTML;
            } else {
                cell.innerHTML = $(cols[i]).value;
            }
        }
        cell = row.insertCell(i);
        cell.innerHTML = '<a href="javascript:void(0)" onclick="deleteRow(this.parentNode)" class="delete">törlés</a>';
    }
}

/* addPublisher - deprecated, see addPublisherAC */
function addPublisher(t, r) {
    $("emptypub").style.display = "none";
    addRow(t, r);
    var cols = r.split(";");
    if ($(t)) {
        if (cols[1]) {
            $(t).rows[1].cells[0].innerHTML += '<input type="hidden" name="publishers[' + $(cols[0]).value + ']" value="' + $(cols[1]).value + '" />';
        } else {
            $(t).rows[1].cells[0].innerHTML += '<input type="hidden" name="publishers[]" value="' + $(cols[0]).value + '" />';
        }
    }
}
/**
  * replacement for addPublisher to use autocomplete
  * t: String   - id of the table html element to put the item data in
  * r: String   - id of the text input where the user types in for AC
  * x: String   - id of the hidden input to store the seleted item's database ID
  */
function addPublisherAC(t, r, x) {
    $("emptypub").style.display = "none";
    addRow(t, r);
    var cols = r.split(";");
    if ($(t)) {
        if (cols[1]) {
            $(t).rows[1].cells[0].innerHTML += '<input type="hidden" name="publishers[' + $(x).value + ']" value="' + $(cols[1]).value + '" />';
            $(cols[1]).value = "";
            $(cols[0]).value = "";
        } else {
            $(t).rows[1].cells[0].innerHTML += '<input type="hidden" name="publishers[]" value="' + $(x).value + '" />';
            $(cols[0]).value = "";
        }
    }
}

function addContent(table, sourceid, fid, hid, type) {
    if ($(sourceid).value) {
        hideItem(table);
        hideItem("empty_" + table);
        showItem("load_" + table);
        $("add_ajaxloader_id").value = "load_" + table;
        $("add_ajaxcomplete_id").value = table;
        $("add_art_type").value = type;
        $(hid).value = $(sourceid).value;
        $(fid + "_submit").click();
    }
}

function addSingleRow(table, row, emptyrow, hiddenname) {
    $(emptyrow).style.display = "none";
    addRow(table, row);
    var cols = row.split(";");
    if ($(table)) {
        $(table).rows[1].cells[0].innerHTML += '<input type="hidden" name="' + hiddenname + '[]" value="' + $(cols[0]).value + '" />';
    }
}

function addSingleRowAC(table, row, callback, emptyrow, hiddenname, idholder) {
    if ($(idholder).value == "") {
        return;
    }
    $(emptyrow).style.display = "none";
    addRow(table, row);
    var cols = row.split(";");
    if ($(table)) {
        $(table).rows[1].cells[0].innerHTML += '<input type="hidden" name="' + hiddenname + '[]" value="' + $(idholder).value + '" />';
    }
    if (callback != false) {
        eval(callback);
    }
    $(cols[0]).value = "";
    if ($(cols[1])) {
        $(cols[1]).value = "";
    }
}

function updateEditForm(sel, fid, hid) {
    showLoader("layer", true);
    $(hid).value = sel.value;
    $(fid + "_submit").click();
}

function updateSelect(source, selectid, fid, hid, did) {
    hideItem(selectid);
    showLoader(did, false);
    $("ajaxloader_id").value = did;
    $("ajaxcomplete_id").value = selectid;
    $(hid).value = source.value;
    $(fid + "_submit").click();
}

function showLoader(did, fixed) {
    var ih = '';
    if (fixed) {
        ih += '<table style="width: 800px; height: 500px;">';
    } else {
        ih += '<table style="width: 100%; height: 100%;">';
    }
    ih += '<tr><td style="width: 100%; height: 100%; vertical-align: middle; text-align: center;">';
    ih += '<img src="/images/ajax-loader.gif" alt="Loading..." title="Loading..." /></td></tr></table>'
    $(did).innerHTML = ih;
}

/**
  *  general TEST functions
  */
  
function getFirstChild(parent, childTagName) {
    for (var i = 0; i < parent.childNodes.length; i++) {
        if (parent.childNodes[i]) {
            if (parent.childNodes[i].nodeName) {
                if (parent.childNodes[i].nodeName.toLowerCase() == childTagName.toLowerCase()) {
                    return parent.childNodes[i];
                } else {
                    var sub = getFirstChild(parent.childNodes[i], childTagName);
                    if (sub) {
                        return sub;
                    }
                }
            }
        }
    }
    return false;
}

function langInRow(row) {
    var x = getFirstChild(row, "input");
    if (x) {
        x = x.value;
    }
    return x;
}

function test(x) {
    alert(x);
}

/**
  * autocomplete functions
***/

function globalClickHandler() {
    if ($("autoCompleteDiv").canClose) {
        $("autoCompleteDiv").style.display = "none";
    }
    $("autoCompleteDiv").canClose = true;
}
function selectItem(w) {
    var inputid = w.getAttribute("id").substr(0, w.getAttribute("id").indexOf("_select"));
    $(inputid).value = w.options[w.selectedIndex].innerHTML;
    $(inputid + "_id").value = w.options[w.selectedIndex].value;
    $("autoCompleteDiv").canClose = true;
    globalClickHandler();
    $(inputid).focus();
}
function selectItemMulti(w) {
    var inputid = w.getAttribute("id").substr(0, w.getAttribute("id").indexOf("_select"));
    var baseval = $(inputid).value.substr(0, $(inputid).value.lastIndexOf(";") + 1);
    $(inputid).value = baseval + " " + w.options[w.selectedIndex].innerHTML + "; ";
    $(inputid + "_id").value += ";" +  w.options[w.selectedIndex].value;
    $("autoCompleteDiv").canClose = true;
    globalClickHandler();
    $(inputid).focus();
    /* look for callback functions.. (was an attribute before, like of selectItemAndCall) */
    if (inputid == "szerzok_ac" && typeof(reloadArticlesAC) == "function") {
        /* this happens on page: books */
        reloadArticlesAC();
    } else if (inputid == "szerzok_ac" && typeof(reloadAuthorArticles) == "function") {
        /* this happens on page: articles */
        reloadAuthorArticles();
    }
}
function selectItemAndCall(w, callback) {
    selectItem(w);
    eval(callback + '()');
}
function selectItemMultiAndCall(w, callback) {
    selectItemMulti(w);
    eval(callback + '()');
}
function autoCompleteDone() {
    hideItem($("ac_loader"));
    showItem("ac_select-holder");
}
/**
  * delayed data collector
  */
function fireAutoComplete() {
    var d = $("autoCompleteDiv");                               // container of all ac objects
    var input = d.firedInput;                                   // stored current input
    var acval = input.value;
    if (acval.indexOf(";") > -1 && acval.lastIndexOf(";") > input.selectionStart - 1) {
        return;
    }
    acval = acval.substr(acval.lastIndexOf(";") + 1).strip();
    var list = $(d.firedInput.getAttribute("id") + "_select");  // dropdown of current ac
    if ($("ac_loader")) {                                       // if loader exists
        showItem($("ac_loader"));                               // show loader
    } else {                                                    // if loader does not exists
        var acloader = document.createElement("div");           // create loader's container
        acloader.setAttribute("id", "ac_loader");               // set up loader attributes
        acloader.style.width = "100%";                          // set up loader styles
        acloader.style.padding = "60px 0";                      // set up loader styles
        acloader.style.textAlign = "center";                    // set up loader styles
        acloader.style.backgroundColor = "#ffffff";             // set up loader styles
        d.appendChild(acloader);                                // add loader container element to ac container
        acloader.innerHTML = '<' + 'img src="/images/ajax-loader-snake.gif" alt="" />'; // add image to loader container
    }
    hideItem("ac_select-holder");                               // container of ac selects (and nothing else)
    if (input.value.length > -1) {                              // if input does exists
        d.style.display = "block";                              // show ac container
        var all = d.descendants();                              // get children of ac container
        for (var i = 0; i < all.length; i++) {                  // cycle through ac container's children
            if (all[i].nodeName.toUpperCase() == "SELECT") {    // if iterated element is a select
                all[i].style.display = "none";                  // hide iterated select
            }
        }
        list.style.display = "inline";                          // show current select
        d.style.top = String(input.cumulativeOffset().top + input.getHeight()) + "px";
        d.style.left = String(input.cumulativeOffset().left) + "px";
        d.style.width = String(input.getWidth() - 2) + "px";
        $("ac_filter").value = acval;                           // store typed value to remoter form
        $("ac_input").value = input.getAttribute("id");         // store current input's id to remoter form
        $("submit_ac").click();                                 // submit remoter form
    }
}
/**
  * input: Object   - the text input element where the user types
  * event: Object   - the event object
  *
  * will start gather data after some delay
  */
function autoComplete(input, event) {
    var d = $("autoCompleteDiv");       // all ac select's container
    if (input.delayer) {                // if a delayed ac is already started
        clearTimeout(input.delayer);    // clear the delayed one (will start new)
    }
    d.firedInput = input;               // store the caller object in the container
    if (d.style.display == "block" && event && event.keyCode == 40) {           // DOWN arrow pressed and ac select already shown
        var list = $(d.firedInput.getAttribute("id") + "_select");              // get the currrent ac select
        list.focus();                                                           // focus on the current ac select
    } else if (d.style.display == "block" && event && event.keyCode == 27) {    // ESC pressed and ac select already shown
        var list = $(d.firedInput.getAttribute("id") + "_select");              // get the currrent ac select
        list.blur();                                                            // focus off from the current ac select
        d.style.display = "none";                                               // hide ac container
    } else if (d.style.display == "block" && event && event.keyCode == 13) {    // ENTER pressed and ac select already shown
        var list = $(d.firedInput.getAttribute("id") + "_select");              // get the currrent ac select
        if (input.getAttribute("id") == "qsearch_ac") {                         // if ENTER was pressed on quicksearch input, just hide
            list.blur();                                                        // focus off from the current ac select
            d.style.display = "none";                                           // hide ac container
            return;                                                             // skip handling enter event
        }
        if (list.selectedIndex > -1) {                                          // if there is a selected option
            list.onclick();                                                     // invoke click on selected option
        } else if (list.options.length > 0) {                                   // if there is no selected option
            list.selectedIndex = 0;                                             // select first option
            list.onclick();                                                     // invoke click on selected option
        }
        list.blur();                                                            // focus off from the current ac select
        d.style.display = "none";                                               // hide ac container
    } else if (event && event.keyCode == 32) {                                  // do not fire on space
        return;
    } else {                                                                    // if ac container is still hidden or letter key pressed
        input.delayer = setTimeout(fireAutoComplete, 1000);                     // call delayed function to gather reqested data
    }
}
function autoCompleteFiltered(input, filterid, event) {
    $("ac_subfilter").value = $(filterid).value;
    autoComplete(input, event);
}

function keySelect(select, event) {
    if (event && event.keyCode == 13) {
        selectItem(select);
    }
}
function keySelectMulti(select, event) {
    if (event && event.keyCode == 13) {
        selectItemMulti(select);
    }
}
function keySelectAndCall(select, callback, event) {
    if (event && event.keyCode == 13) {
        selectItemAndCall(select, callback);
    }
}
function keySelectMultiAndCall(select, callback, event) {
    if (event && event.keyCode == 13) {
        selectItemMultiAndCall(select, callback);
    }
}

// default functions for each ac element where needed
function addPublisherDefaultAC() {
    addPublisherAC('pubtable', 'kiadok_ac', 'kiadok_ac_id');
}
function addIllustratorDefaultAC() {
    addSingleRowAC('illtable', 'illu_ac', false, 'emptyill', 'illustrators', 'illu_ac_id');
}
function addAuthorDefaultAC() {
    addSingleRowAC('authtable', 'szerzok_ac', 'reloadArticlesAC()', 'emptyauth', 'authors', 'szerzok_ac_id');
}

/* change modified data's row */
function mod(id) {
    if ($(id).className.indexOf("modified_row") == -1) {
        $(id).className += " modified_row";
        $(id + "_container").innerHTML += "<span> - szerzősége megváltozott!</span>"
    }
}

/* adjust helper data (callback) */
function adjustHelp() {
    var t = $("authortable");
    var c = t.descendants();
    for (var i = 0; i < c.length; i++) {
        var x = c[i];
        if (x.nodeName && x.nodeName.toLowerCase() == "td") {
            if (x.className == "imp") {
                x.className = "";
            }
            if (x.innerHTML.indexOf("deleteRow") > -1 && x.innerHTML.indexOf("editperson") == -1) {
                var newLinks = "";
                var pid = $(x).previous('td').down(0).value;
                newLinks += '<a href="/people/editperson/' + pid + '">szerkesztés</a>';
                newLinks += ' | ';
                newLinks += '<a href="javascript:void(0)" class="delete" onclick="mod(\'edited_article\');deleteRow(this.parentNode)">törlés</a>';
                x.innerHTML = newLinks;
                mod('edited_article');
            }
        }
    }
}

/* move to page */
function moveToPage() {
    $("qjumpto").value = $("qs_auth_ac_select").value;
    $("qjump").submit();
}

/* - */

Event.observe(window, 'load', function() {
    if ($("autoCompleteDiv")) {
        $("autoCompleteDiv").canClose = true;
        Event.observe($("autoCompleteDiv"), 'mouseup', function () { $("autoCompleteDiv").canClose = false; } );
        Event.observe(window, 'mouseup', globalClickHandler);
    }
});

/**
  * end
***/
