/*******************************************************************************
 * Serializaes drops - saves drops with their images into string and then into cookie
 ******************************************************************************/ 
function SerializeDrops(){
  var drop = $('drop_list').getElementsByClassName('drop_place');
  var dropPlaces = "";
  
  for (var i = 0; i < drop.length; i++) {
    if (drop[i].childElements().length > 0) {
      dropPlaces += ((((drop[i].childElements())[0]).childElements())[0]).src + "|";
    } else {
      dropPlaces += "x|";
    }
  }
  //passing 'dropPlaces' through form field is not used
  
  try {
    document.forms['sendForm0'].elements['SerializedDrops'].value  = dropPlaces;
  } catch (err) {
    //do nothing
    //work only if SendForm is displayed
    //also IE7+ throws error
  }
  SetCookie ("SerializedDrops", dropPlaces, null, "/");
  //DBG("dropPlaces:"+dropPlaces+"|");
  return dropPlaces;
}
  
/*******************************************************************************
 * debug print
 ******************************************************************************/ 
function DBG(txt) {
  document.getElementById('footer').innerHTML += "<br>"+txt;
}
/*******************************************************************************
 * Removes previously set icons - deletes cookies and reloads page
 ******************************************************************************/ 
function removeAllIconsFromDrops(){
  DeleteCookie("SerializedDrops", "/");
  window.location.reload();
}


function assignLIElement(e) {
  //create the dropplace
  var li = $(document.createElement("li"));
  li.className = "drop-attr-empty";
  var div = $(document.createElement("div"));
  div.className = "icon icon-size-1.3";
  //e.appendChild(li).appendChild(div);
  li.appendChild(div);
  return li;
}
function assignIcon(e, imgSrc) {
  //create the complete elements with the icon
  var div = $(document.createElement("div"));
  div.className = "icon icon-size-1.3";
  var img = $(document.createElement("img"));
  img.src = imgSrc;
  e.appendChild(div).appendChild(img);
  handleIconDisplayDrop(div);
}
/*******************************************************************************
 * Initially fill the drop places with icons - only if there were selected icons
 ******************************************************************************/ 
function fillDroppabbles(){

  var cookie =  GetCookie ("SerializedDrops");
  if (cookie != null) {
  
    var imgsrc = cookie.split("|");
    var drop = $('drop_list').getElementsByClassName('drop_place');

    for (var i = 0; i < drop.length; i++) {
      if (imgsrc[i]!= "x") {
        //create the complete elements with the icon
        assignIcon(drop[i], imgsrc[i]);
      }
    }
  }
}

function checkIcons(){
     var cookie =  GetCookie ("SerializedDrops");
  if (cookie != null) {
  var count = 0;
  
    var imgsrc = cookie.split("|");
    var drop = $('drop_list').getElementsByClassName('drop_place');

    for (var i = 0; i < drop.length; i++) {
      if (imgsrc[i]!= "x") {
        count++;
      }
    }
  }
  
     if (!count) {
        alert('Musíš zvolit alespoň jednu ikonu');
        return false;
    }
}

function initCard() {
// Skryti na zaklade tridy
// if ($('main_container').getElementsByClassName('flash-info')) {
//    //alert('before hide');
//    var elm = $('main_container').getElementsByClassName('flash-info');
//    for (var i = 0; i < elm.length; i++) {
//    	elm[i].hide.delay(10);
//      }
// }
	
// skryti s delaye na zaklade id
 if (document.getElementById('flashes'))  Element.hide.delay(3, $('flashes'));

 //Initially fill the drop places with icons
  fillDroppabbles();
  // zpracujeme nazev pohlednice
  if (!GetCookie('card_name') && $("default_card_name")) $("card_name").value = $("default_card_name").value;
  else if ($("card_name")){
        if ($("card_name").value != $("default_card_name").value)  {	
        if ($("card_name") && GetCookie('card_name')) {
            $("card_name").value = GetCookie('card_name');
            if ($("card_name_input")) $("card_name_input").value = GetCookie('card_name');
        }
      	if ($("card-nazev") && GetCookie('card_name')) $("card-nazev").innerHTML = GetCookie('card_name');
       }
  }

 try {
    prepareDrops();
 } catch (err){
    //do nothing
    //used for generating in SENDFORM page
 }
 try {
    prepareDrags();
 } catch (err){
    //do nothing
    //used for generating in SENDFORM page
 }
 try {
    Droppables.add($("icon-trash"), {
      hoverclass: "icon-trash-hover",
      onDrop: onIconTrashDrop
    });
 } catch (err){
    //do nothing
    //used for generating in SENDFORM page
 }
}

function onIconTrashDrop(e, trash){
  if ($(e).tagName.toUpperCase() == "LI"){
    try {
      var first_child = getFirstChild(e);
      var child_of_child = getFirstChild(first_child);
      child_of_child.remove();
      //getFirstChild(e).removeChild(getFirstChild(getFirstChild(e))); //doesn't work with IE7+
    } catch (err) {
      //do nothing
    }
  }
}


function handleIconDisplayDrop(e) {
  getFirstChild(e).addClassName("in_drop_place");
}
function handleIconDisplayDrag(e) {
  getFirstChild(e).removeClassName("in_drop_place");
}

function CustStartEff(e){
  e = $(e);
  handleIconDisplayDrag(e);
  //this.MPoriginalParent.appendChild(e);
//   SerializeDrops();
}

/*******************************************************************************
 * Gets all child elements of a node (but not descendant nodes) and ignores text nodes
 * For IE use only 
 ******************************************************************************/ 

function getChildElements (node)
{
    var a = [];
    var tags = node.getElementsByTagName("*");
    
    for (var i = 0; i < tags.length; ++i) {
        if (node == tags[i].parentNode) {
            a.push(tags[i]);
        }
    }
    return a;
} 

/*******************************************************************************
 * Function delete all given nodes.
 * Idependently of their parents. 
 ******************************************************************************/ 
function deleteNodes(children){
 for(i=0; i< children.length; i++) {
      //par.removeChild(children[i]);
      children[i].parentNode.removeChild(children[i]);
    }
}


function getFirstChild(e){
  return getChildElements(e)[0];
}

// callback pri polozeni ikony do pohlednice
// @param draggable ikona
// @param droppable misto v pohlednici
function onDropFnc(draggable, droppable){
  // jeste tam nic neni, vytvorim ikonu a prispendlim ji tam
  draggable = $(draggable);
  droppable = $(droppable);


 if (droppable.childElements().length == 0){  	// (childElements() ignoruje textove uzly)
//     droppable.insert(draggable);
    var icon = new Icon(draggable);

//      icon.div.addClassName("in_drop_place");
// draggable.addClassName("in_drop_place");

//   handleIconDisplayDrop(draggable);
  
  assignIcon(droppable, getFirstChild(draggable).src);
  //handleIconDisplayDrop(draggable);

    
    //icon.makeDraggable();
    $(droppable.parentNode).addClassName("movable");
	// presun drop_place -> drop_place : starou ikonu smazu
    if (draggable.hasClassName("in_drop_place")){
      draggable.remove();
    }
	    
  }
//    SerializeDrops();
}



function prepareDrags() {

  var icons = $('catalog').getElementsByClassName('icon');
  //var icons = document.getElementsByClassName('icon');
  for (var i = 0; i < icons.length; i++) {
    var opt = { revert : true, ghosting : false, zindex: false, starteffect: CustStartEff,MPoriginalParent: icons[i].parentNode};
    new Draggable(icons[i], opt);

  }
  
}

// "ozivi" mista v pohlednici
function prepareDrops(){

  var drops = $A($("drop_list").getElementsByClassName('drop_place'));

  var opt = {};

  for (var i = 0, dlen = drops.length; i < dlen; i++){
    var drop = drops[i];
//     var w = parseInt(drop.getStyle("width"));
//     var h = parseInt(drop.getStyle("height"));

    var opt = {
      //accept: 'icon-size-' + (Math.floor(parseFloat(w / h) * 10) / 10),
      accept: 'icon',
      hoverclass: "drop_place_hover",
      onDrop: onDropFnc
    };
   Droppables.add(drop, opt);
  }

  Sortable.create("drop_list", {constraint: ""});
  Sortable.onMyChange = function(){
    SerializeDrops();
  }
}


function clearInputBox(id,text){
	if (document.getElementById(id).value == text){
		document.getElementById(id).value = '';
	}
}

function inputTextToSession (id){
	var text = '';
	
	text = document.getElementById(id).value;
	default_text = document.getElementById('default_card_name').value;
	
	if (text!=default_text)	SetCookie ("card_name" , text , null , "/" );
	/*
	akce = document.getElementById(polozka+""+id).alt;
	
	var option = {
	metdhod : "get",
	asynchronous : true,
	onSuccess : function(t){ alert('ok'); },
	onFailure : function(t){ 
		ajax_error(t.status, t.statusText); }
	};
	new Ajax.Request("scripts/ajax.php?akce=input_text_to_cookies&text="+text, option);	
	*/
}

