//
// Created on: <9-Oct-2006 14:18:58 ar>
//
// ## BEGIN COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
// SOFTWARE NAME: eZ publish
// SOFTWARE RELEASE: 3.9.x
// COPYRIGHT NOTICE: Copyright (C) 1999-2006 eZ systems AS
// SOFTWARE LICENSE: GNU General Public License v2.0
// NOTICE: >
//   This program is free software; you can redistribute it and/or
//   modify it under the terms of version 2.0  of the GNU General
//   Public License as published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of version 2.0 of the GNU General
//   Public License along with this program; if not, write to the Free
//   Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//   MA 02110-1301, USA.
//
//
// ## END COPYRIGHT, LICENSE AND WARRANTY NOTICE ##
//

/*! \file common_ezjaxx.js
*/


//Functions for Contentstructure menu!
function menuAction(e,el){
  var i = menuLinks.indexOf(el), target = menuTargets[i];
  if (el.childNodes[0].src.indexOf(menuAjaxImage.open) == -1){
     el.childNodes[0].src = menuAjaxImage.open;
  } else {
     el.childNodes[0].src = menuAjaxImage.close;
     if (target.getElementsByTagName('a').length == 0)
        menuTargets.load(menuAjaxRoot + "/" + target.parentNode.id.replace(/n/,""), target);
  }
  menuTargets.toggle(i);
}

function menuAjaxLoad(r, el){
    if ($$('input[name=Login]', el).length > 0) document.location=document.location;
    menuTargets.merge($$('ul.subMenu', el));
    menuLinks.merge($$('a.openclose', el).voidLink().click(menuAction));
}


//Functions for Keyword droppdown
function ezInputKeywordPress(e, el, i){
	clearTimeout(ezInputKeywordTimeout);
  	e = e || window.event;
	//cancle that the event bubbles up to the form element
  	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	var c = e.keyCode || e.which;
	var keyword = el.value.split(',').pop().trim();
	//break any futher action on specific keys like backspace
	if (c == 44 || c == 8 || c == 188 || c == 32 || keyword.length < 1) return true;
	else if ((c == 38 || c == 40) && ezKeywordDropdownLI != 0) return ezInputKeywordSelect(c);
	else if (c == 13) return ezInputKeywordEnter(el);
	ezKeywordDropdown.hide();
	ezKeywordIndex = i;
	ezInputKeywordTimeout = setTimeout(ezKeywordAjaxObject.load.bind(ezKeywordAjaxObject,ezjaxxRootUrl + '/keyword/' + (( ezEditClassID !== undefined && ezEditClassID) ? ezEditClassID : ''), 'Keyword='+ keyword + String.fromCharCode(c) ), ((c == 46) ? 350 : 230));
	return true;
}

function ezInputKeywordSelect(c, i){
	i = ezKeywordDropdownIndex;
    ezKeywordDropdownIndex = i = (i < 0) ? 0 : i + c - 39;
	ezKeywordDropdownIndex = i = (ezKeywordDropdownLI.length <= i) ? ezKeywordDropdownLI.length : i;
    if(i > 0) ezKeywordDropdownLI.addClass("selected", i-1);
	else ezKeywordDropdownLI.removeClass("selected");
    return false;
}

function ezInputKeywordMouse(el, i){
    ezKeywordDropdownIndex = i = ezKeywordDropdownLI.indexOf(el) +1;
    if(i > 0) ezKeywordDropdownLI.addClass("selected", i-1);
	else ezKeywordDropdownLI.removeClass("selected");
    return false;
}

function ezInputKeywordEnter(el){
    if (ezKeywordDropdownLI != 0 && ezKeywordDropdownIndex > 0){
       var arr = el.value.split(',');
       arr[arr.length -1] = ' ' + ezKeywordDropdownLI[ezKeywordDropdownIndex-1].innerHTML;
       el.value = arr.join(',');
       el.focus();
    }
   ezKeywordDropdownIndex = 0;
   ezKeywordDropdown.hide();
   return false;
}

function ezInputKeywordLoad(r){
    ezKeywordDropdown.set(r.responseText);
    var pos = ezInputKeyword.p[ezKeywordIndex];
    ezKeywordDropdown.setStyle({
		top: pos.pt + pos.oh + 'px',
		left: pos.pl + 'px',
		width: pos.ow + 'px'
	});
    ezKeywordDropdownLI = $$('li', ezKeywordDropdown[0]);
    ezKeywordDropdown.fx().show();
}


//Functions for object relations drag and drop
function relationsAjaxLoad(r, el){
	var dragobject = $$('li.draggable span', el);
	if (dragobject.length != 0){
		dragobject.drag(searchObjectRelation);
		dragobject.o.selected = "dragselected";
		dragobject.o.onDrop = relationsAjaxDrop.bindE(dragobject);
		dragobject.setStyle({
			cursor: "move",
			backgroundColor: "#efefe8",
			position: "relative",
			top: "0px",
			left: "0px",
			zIndex: 99 
		});
	}
}

function relationsAjaxDrop(el){
    if (el.style){
    	el.style.top = 0 + 'px';
    	el.style.left = 0 + 'px';
    }
    if (this.odpi != this.dpi){
       el = el.parentNode;
       var target = this.dp[this.dpi], targetHiddenID = $$('input[type=hidden]', target);
       var targetP = $$('p', target), targetTable = $$('table', target), elHidden = $$('input[type=hidden]', el);
       if (targetP.length != 0){
          targetP.remove();
          targetTable.show();
          $$('input.button-disabled', target).removeClass('button-disabled').addClass('button')[0].disabled = false;
       }
       if (targetHiddenID.length != 0){
	       targetHiddenID[0].value = elHidden[0].value;
	       var targetTD = $$('td', target);
	       targetTD[0].innerHTML = el.innerHTML;
	       targetTD[1].innerHTML = elHidden[1].value;
	   } else {
	       var targetTR = $$('tr', targetTable), targetTD = $$('td', targetTR[1]);
           if (targetTD[1].innerHTML != ""){
                var newTR = targetTR[1].cloneNode(true);
                targetTable[0].appendChild(newTR);           
           }
           targetTR = $$('tr', targetTable);
           targetTD = $$('td', targetTR[targetTR.length - 1]);
           targetTD[1].innerHTML = $$('span', el)[0].innerHTML;
           targetTD[0].firstChild.value = elHidden[0].value;
           targetTD[2].innerHTML = elHidden[1].value;
           var targetOffset = 0;
           $$('input[type=text]', targetTable).forEach(function(el, i, t){
               if (t.length > 1 && el.value > targetOffset) targetOffset = el.value;
           });
           targetOffset++;
           targetTD[4].firstChild.value = targetOffset;
           
           //now 'all' we have to do is post the changes over ajax..
           targetHiddenID = $$('input[type=hidden]', target.parentNode)[0].value;
           var formStr = "SelectedObjectIDArray[]=" + elHidden[0].value;
           formStr = formStr + "&CustomActionButton[" + targetHiddenID + "_set_object_relation_list]=Test";
           formStr = formStr + "&ContentObjectAttribute_id[]=" + targetHiddenID;
           formStr = formStr + "&ContentObjectAttribute_priority[" + targetHiddenID + "][]=" + (targetOffset);
           formAjaxPostBack.load($('editform')[0].action, formStr);
	   }
       searchres.hide();
       searchform.show();
	}

}

//Width Control functions
function ezjaxxWidthControl(el, i){
	if (el.tagName == "A"){
		var arr = el.href.split("/"), width = arr.pop(), key = arr.pop();
		el.href = "JavaScript:ezjaxxSetLeftMenuWidth('" + key + "', '" + width + "')";
	} else {
		var x = 0, width;
		for (attr in ezjaxxWidthSize){
			if (x == i) width = attr;
			x++;
		};
		var newA = document.createElement("a");
		newA.href = "JavaScript:ezjaxxSetLeftMenuWidth('admin_left_menu_width', '" + width + "')";
		newA.innerHTML = el.innerHTML;
		newA.className = 'selected';
		el.parentNode.replaceChild(newA,el);
	}
}

function ezjaxxSetLeftMenuWidth(key, width){
    new $ajax({ method: "GET" }, ezjaxxRootUrl + "/preferences/set/" + key + "/" + width);
    var leftmenu = $('leftmenu'), size = ezjaxxWidthSize[width], x = 0;
	leftmenu[0].style.width = size + "em";
    $('maincontent')[0].style.marginLeft = (size + 0.5) + "em";
	for (attr in ezjaxxWidthSize){
			if (width == attr) break;
			x++;
	};
	ezjaxxWidthElements.slide(x);
}

// Copy here Function
function ezjaxxCopyHere(u, parentNodeID){
	ezpopmenu_hideAll();
	var copyForm = $('child-menu-copy-here-form')[0], copyDiv = $('copy_here_form');
	var objectID = CurrentSubstituteValues['%objectID%'];
	copyDiv.hide();
	copyForm.action = u + "/" + objectID;
	copyForm.parentNodeID.value = parentNodeID;
	copyForm.NodeID.value = CurrentSubstituteValues['%nodeID%'];
	copyForm.ObjectID.value = objectID;
	copyDiv.setStyle({
		top: ($getScroll().st + 220) + 'px'
	});
	copyDiv.fx({duration: 200, height: true}).show();
	return false;
}

//things todo when document is loaded
$addEvent(window, 'load', function(){

	//Fixes toggle boxes that still use ezjs_toggleCheckboxes
	$$('img[onclick^=ezjs_toggleCheckboxes]').forEach(function(el){
		el.onclick = function(){$$('input[type=checkbox]',this.parentNode.parentNode.parentNode).check();return false};
	});

	//class edit attribute up / down
	//var temp = $$("input[name^=MoveDown]");
	//if (temp.length > 0) alert('Down: ' + temp.length + ' Up:' + $$("input[name^=MoveUp]").length);

	// menu width code
	$$('div.widthcontrol p *').forEach(ezjaxxWidthControl);
	ezjaxxWidthElements = $$('div.widthcontrol a').fx({display:''});

});//$addEvent(window, 'load')