//
// 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.setStyle({
			cursor: "move",
			backgroundColor: "#efefe8",
			position: "relative",
			top: "0px",
			left: "0px",
			zIndex: 99 
		});
		dragobject.drag( searchObjectRelation );
		dragobject.o.selected = "dragselected";
		dragobject.o.onDrop = relationsAjaxDrop.bindE(dragobject);
	}
}

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[name*=data_object_relation_id]', 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
	   { 
	   //this is objectrelations, meaning we will have to do a bit more
	       var targetTR = $$('tr', targetTable), targetTD = $$('td', targetTR[1]);
           if (targetTD[1].innerHTML != "")
           {
                var newTR = targetTR[1].cloneNode(true);
                targetTR[1].parentNode.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..
           var targetAttributeID = $$('input[name^=ContentObjectAttribute_id]', target.parentNode)[0].value;
           var formStr = "SelectedObjectIDArray[]=" + elHidden[0].value;
           formStr = formStr + "&CustomActionButton[" + targetAttributeID + "_set_object_relation_list]=Test";
           formStr = formStr + "&ContentObjectAttribute_id[]=" + targetAttributeID;
           formStr = formStr + "&ContentObjectAttribute_priority[" + targetAttributeID + "][]=" + (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;
}

var classEditAjax = 0;

function classEditUpDown(e)
{
    e = e || window.event;
    var classAttribute = ( e.target || e.srcElement ).name.split('_');
    var classEditUri = $$("form[name=ClassEdit]")[0].action.split('class/edit/')[0];
    classEditUri += 'jaxx/classattribute/' + classAttribute[1] + '/' + classAttribute[0] + '/';
    classEditAjax.load( classEditUri );
    return false;
}

function classEditLoad(r)
{
   if ( r.getResponseHeader("Content-Type").indexOf('text/xml') != -1 ) classEditAddHtml( r.responseText );
   else eval( r.responseText );
}

function classEditUpDownMove( id, dir )
{
   var attributes = $$('input[name^=ContentAttribute_is_required_checked]'), indexOfCurrent = -1, moveDown = (dir == 'MoveDown'), indexOfSwap = -1;
   attributes.forEach(function(el,i){
      if (el.value == id) indexOfCurrent = i;
   });
   if (!moveDown && indexOfCurrent == 0)
      indexOfSwap = attributes.length -1;
   else if (moveDown && indexOfCurrent == attributes.length -1)
      indexOfSwap = 0;
   else if (indexOfCurrent != -1)
      indexOfSwap = indexOfCurrent + ((moveDown) ? 1 : -1);

   if (indexOfCurrent == -1 || indexOfSwap == -1) return alert("Something gone wrong in classEditUpDownAnimate in ezjaxx!");
   
   var table = attributes[indexOfCurrent].parentNode.parentNode.parentNode.parentNode.parentNode;
   var pos = $$('input[name^=ContentAttribute_position]', table);
   var pri = $$('input[name^=ContentAttribute_priority]', table);
   
   pos[indexOfCurrent].value = indexOfSwap +1;
   pos[indexOfSwap].value = indexOfCurrent +1;
   
   if (pri.length > 0) //3.9 code
   {
      pri[indexOfCurrent].value = indexOfSwap +1;
      pri[indexOfSwap].value = indexOfCurrent +1;
   } else pri = $$('input[name^=MoveUp_]', table);
   
   
   if (moveDown && indexOfSwap != 0)
   {
      table.insertBefore(  pos[ indexOfSwap ].parentNode.parentNode, pri[ indexOfCurrent ].parentNode.parentNode.parentNode );
      table.insertBefore( pri[ indexOfSwap ].parentNode.parentNode.parentNode, pos[ indexOfSwap ].parentNode.parentNode );
   }
   else
   {
      table.insertBefore(  pos[ indexOfCurrent ].parentNode.parentNode, pri[ indexOfSwap ].parentNode.parentNode.parentNode );
      table.insertBefore( pri[ indexOfCurrent ].parentNode.parentNode.parentNode, pos[ indexOfCurrent ].parentNode.parentNode );
   }
   
   if (indexOfCurrent == 0 && indexOfSwap == attributes.length -1)
   {
      table.insertBefore(  pos[ indexOfSwap ].parentNode.parentNode, pri[ indexOfCurrent ].parentNode.parentNode.parentNode );
      table.insertBefore(  pri[ indexOfSwap ].parentNode.parentNode.parentNode, pos[ indexOfSwap ].parentNode.parentNode );
   }
}

function classEditAdd(e)
{
    e = e || window.event;
    var el = $('DataTypeString')[0], classId = 0;
    var classEditUri = $$("form[name=ClassEdit]")[0].action.split('class/edit/');
    classId = classEditUri[1].split('/')[0], classEditUri = classEditUri[0]; 
    classEditUri += 'jaxx/classattribute/' + classId + '/Add/' +  el.options[ el.selectedIndex ].value;
    classEditAjax.load( classEditUri );
    return false;
}

function classEditAddHtml( html )
{
   var table = $$('table.list', $$("form[name=ClassEdit]")), temp = document.createElement("div"), tr;
   if (table.length == 0) ;//reload page;
   
   table  = table[0];
   var tbody = $$('tbody', table);
   if (tbody.length != 0 && tbody[0].parentNode == table) table = tbody[0];
   
   temp.innerHTML = '<table>' + html + '</table>'; //tables.innerHTML is read only in ie
   table.appendChild( temp.getElementsByTagName('tr')[0] ); 
   table.appendChild( temp.getElementsByTagName('tr')[0] );
   
    $$("input[name^=MoveDown_]", "input[name^=MoveUp_]", table).forEach(function(el){
		el.onclick = classEditUpDown;
	});
}


//things todo when document is loaded
$addEvent(window, 'load', function()
{
	//class edit attribute up / down
	var classEdit = $$("input[name^=MoveDown_]", "input[name^=MoveUp_]");
	if (classEdit.length > 0)
	{
	    $$('input[name=NewButton]')[0].onclick = classEditAdd;
		classEdit.forEach(function(el){
		    el.onclick = classEditUpDown;
		});
		classEditAjax = new $ajax({ onLoad: classEditLoad, noCache: true });
	}

	// menu width code
	$$('div.widthcontrol p *').forEach(ezjaxxWidthControl);
	ezjaxxWidthElements = $$('div.widthcontrol a').fx({display:''});
});

