var isIe = (document.all);
var isGecko = !isIe;

var php_self=null;

function validate_numeric(field){
	field.value = field.value.replace(/[^0-9]/g, "");
}

function get_php_self(){
	if (php_self == null){
		php_self = location.href;
	  if (php_self.indexOf('?')!=-1){
	  	php_self = php_self.substring(0, php_self.indexOf('?'));
	  }
  }
  
  return php_self;
}

/**
 * Carga los modelos para la marca seleccionada
 */
function load_modeles(marque){
  var sUrl = get_php_self()+'?action=modeles&mid=' + url_encode(marque) ;

  // vacio los combos
  clearSelects('modelesId');

  if (marque != ''){
    setEnableState(false,'wizard_v_modele');

    var oXML = new FCKXml();
    oXML.LoadUrl( sUrl, load_modeles_callback) ;  // Asynchronous load.
  }
}

/**
 * Funcion callback ejecutada cuando el servidor devuelve el listado de
 * regiones.  Esta funcion cargara el combo con el listado que se encuentra
 * en la respuesta
 *
 * @param fckXml objeto xml que representa la respuesta
 */
function load_modeles_callback(fckXml){
  var oNodes = fckXml.SelectNodes('modeles/modele');
  var cbo = document.getElementById('wizard_v_modele');
  var idx;
  
  for (var i = 0 ; i < oNodes.length ; i++){
    var modele = oNodes[i].attributes.getNamedItem('name').value;
    
    cbo.options[i+1] = new Option(modele,modele);
  }
  
  setEnableState(true,'wizard_v_modele');
}

function setEnableState(b) {
  var d = document;
  var args = setEnableState.arguments;
  var e;
  
  for(var i = 1; i < args.length; i++){
    e = d.getElementById(args[i]);
    if (e)
      e.disabled = !b;
  }
}
function clearSelects() {
  var d = document;
  var args = clearSelects.arguments;
  var cbo;
  var base;
  
  for(var i = 0; i < args.length; i++){
    cbo = d.getElementById(args[i]);
    base = 0;

    if (cbo != null && cbo.options != null){
      for (var j = cbo.options.length; j > base; j--){        
        cbo.options[base+1] = null;
      }
    }
  }
}



function url_encode(url){
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";										// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = url;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}


function url_decode(url){
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = url;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
     var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
  
  return plaintext;
}


var lang = new Array();

CUploader = function(){
	this.uploadInProgress= false;
	this.frame= 'uploadFormDiv';
	this.form= 'fileUploadForm';
	this.status= 'uploadStatusDiv';
	this.iframe= 'upload_target';
	this.uploadFileCount = 1;
	
	/**
   * shows the upload form
   */
	this.show = function(position) {
		if (this.isUploadInProgress()) {
			alert(lang['error_upload_in_progress']);
			return;
		}
		
		$('fileUploadForm').reset();
		$('fileUploadForm').action = get_php_self()+'?action=upload&pos=' + position ;
		
		$("uploadFileHolder").innerHTML = '<input id="NewFile" name="NewFile'+this.uploadFileCount+'" type="file" style="width:300px;" class="textfield" />';
		this.uploadFileCount++;
		
		
		// hide status and show form
		GUI.showElement(this.form);
		GUI.hideElement(this.status);
		
		// show layer
		GUI.showForm(this.frame);
	};
	
	/**
	 * hides the upload form
	 */
	this.hide = function(){
		GUI.hideForm(this.frame);
		
		$(this.form).reset();
		$(this.iframe).src = 'blank.html';
	};

	/**
	 * Checks if another upload is currently in progress
	 */
	this.isUploadInProgress = function() { 
		return this.uploadInProgress; 
	};
	
	/**
	 * uploads a file
	 */
	this.submitUpload = function() {
		if ( document.getElementById('NewFile').value.length == 0 ){
			alert( lang["please-select-a-file-from-your-computer"] ) ;
			return false ;
		}
		
		// hide form and show status
		GUI.hideElement(this.form);
		GUI.showElement(this.status);

		this.uploadInProgress = true;
		
		return true;
	};

	/**
	 * upload is completed
	 */
	this.uploadComplete = function(pos,folder,msg) {
		//var pic = $('picture'+pos);
		var pic2 = $('picture'+pos+'bak');
		var pichidden = $('wizard_v_photo'+pos);

		if (msg.length != 0){
			alert(msg);
			//pic.src = contextPath + ((pos==1)?'/images/photothumbbig.gif':'/images/photothumb.jpg');
			pic2.style.backgroundImage = 'url('+contextPath + ((pos==1)?'/images/photothumbbig.gif':'/images/photothumb.jpg') +')';
			pichidden.value = '0';
		}
		else {
			//pic.src = ((pos==1)?'/images/videothumb2.gif':'/images/photothumb2.gif');
			pic2.style.backgroundImage = 'url('+ folder+'/'+((pos==1)?'':miniprefix)+pos+'.jpg?'+(new Date().getMilliseconds())+')';
			pichidden.value = '1';
		}
		
		$('fileUploadForm').reset();
		this.hide();
		this.uploadInProgress = false;
		
		//browser.reload();
	};
};

var Uploader = new CUploader();


CGUI = function() {

	/**
	 * shows a layer
	 */
	this.showElement = function(name){
		this.__changeElementVisibility(name,'block');
	};
	
	/**
	 * hides a layer
	 */
	this.hideElement = function(name){
		this.__changeElementVisibility(name,'none');
	};

	/**
	 * shows a form
	 */
	this.showForm = function(name){
		this.showElement(name);
		//this.centerElement(name);
		this.disableAll();
	};
	
	/**
	 * hides a form
	 */
	this.hideForm = function(name){
		this.hideElement(name);
		this.enableAll();
	};
	
	/**
   * change the display attribute of the given element
   */
	this.__changeElementVisibility = function(name, state) {
		var element = $(name);
		
		if (element == null) {
			return;
		}
		
		element.style.display = state;
	};
	
	/**
	 * Centers a layer on screen
	 */ 
	this.centerElement = function(name){
		var element = $(name);
		var floatX, floatY;
	
		if (isGecko){ 
			floatX = Math.round((window.innerWidth-20)/2)-Math.round(element.offsetWidth/2);
			floatY = Math.round((window.innerHeight-20)/2)-Math.round(element.offsetHeight/2);
			
			element.style.left = floatX+'px';
			element.style.top = floatY+'px';
	  }
		else if (isIe){
			floatX=Math.round((document.body.offsetWidth-20)/2)-Math.round(element.style.width/2);
			floatY=Math.round((document.body.offsetHeight-20)/2)-Math.round(element.style.height/2);
			
			element.style.left = floatX;
			element.style.top = floatY;
		}
	};
		
	/**
	 * disable all editable fields
	 */
	this.disableAll = function(){
		// todo: disable all editable fields
	};
	
	/**
	 * enable all editable fields
	 */
	this.enableAll = function(){
		// todo: enable all editable fields		
	};
};

var GUI = new CGUI();

var img_last_updated = new Array();

img_last_updated[0] = 0;
img_last_updated[1] = 0;
img_last_updated[2] = 0;
img_last_updated[3] = 0;
img_last_updated[4] = 0;

function gettimestamp(){
	var d = new Date()
	var s=d.getHours()+".";
	s+=d.getMinutes()+".";
	s+=d.getSeconds()+".";
	s+=d.getMilliseconds();
	return s;
}

function onDropPicture(dest_id, element){
  
  var now = gettimestamp();
  var src_id = element.id.substr(7,1);
  
  // obtengo la referencia a los layers
  var dest_bk = $('picture'+dest_id+'bak');
  var src_bk = $('picture'+src_id+'bak');
  
  // marco los timestamp para evitar problemas de sincronia
  img_last_updated[src_id] = now;
  img_last_updated[dest_id] = now;
  
	// obtengo las urls de las imagenes
  var src_url = src_bk.style.backgroundImage;
  var dst_url = dest_bk.style.backgroundImage;
    
  // cambio de forma temporal las imagenes ( se actualizaran desde el evento de ajax )
  dest_bk.style.backgroundImage = get_valid_image_name(dest_id,src_url, src_id);
  src_bk.style.backgroundImage = get_valid_image_name(src_id,dst_url, dest_id);
  
  // cambio el estado de las imagenes
  var dest_hidden = $('wizard_v_photo'+dest_id);
  var src_hidden = $('wizard_v_photo'+src_id);
  var aux = dest_hidden.value;
	dest_hidden.value = src_hidden.value;
  src_hidden.value = aux;
  
  // intercambio las imagenes.
  new Ajax.Request(get_php_self(), {
  	parameters:'action=swappic&p1='+src_id+'&p2='+dest_id+'&ts='+now, 
  	onComplete:function(t){

  		// obtengo el timestamp que corresponde a esta respuesta
  		var xml = t.responseXML;
			var messages = xml.getElementsByTagName('message');
			var rels = $A(messages);
			var ts = rels[0].attributes.getNamedItem("ts").value;

  		// solo actualizo, si no hubieron cambios.
 			if (img_last_updated[src_id] == ts){
 				src_bk.style.backgroundImage = get_valid_image_name(src_id,dst_url,src_id);
 			}
 			if (img_last_updated[dest_id] == ts){
	  		dest_bk.style.backgroundImage = get_valid_image_name(dest_id,src_url,dest_id);
	  	}
  		
  	}});
}

var sec = 1;

function get_valid_image_name(id, filename, changeto){

	var is_default = (filename.indexOf('photothumbbig.gif') != -1 || filename.indexOf('photothumb.jpg') != -1);
  var fn="";  
  var i1 = filename.lastIndexOf('/');
  //var fn = (is_default)?filename.substr(i1+1, filename.length - i1 - 2):filename.substr(i1+1,filename.lastIndexOf('?')-i1-1);

  if (id == 1){
		if (is_default){
			fn = 'photothumbbig.gif';
		}
    else {
      fn = changeto+'.jpg';
    }
	}
  else {
  	if (is_default){
      fn = 'photothumb.jpg';
    }
    else {
      fn = miniprefix+changeto+'.jpg';
    }
  }
  
  if (!is_default){
  	sec++;
  	fn += '?s='+sec+'&t=' + (new Date().getMilliseconds());
  }
  
  var result =filename.substr(0,i1) + '/' + fn + ')'; 
  
  //alert(filename+"\n"+result);
  
  return result;
}

/*

function get_valid_image_name(id, filename, changeto){
	var is_default = (filename.indexOf('photothumbbig.gif') != -1 || filename.indexOf('photothumb.jpg') != -1);
  
  var i1 = filename.lastIndexOf('/');
  var fn = (is_default)?filename.substr(i1+1, filename.length - i1 - 2):filename.substr(i1+1,filename.lastIndexOf('?')-i1-1);
  
  if (id == 1){
		if (is_default){
			fn = 'photothumbbig.gif';
		}
    else {
      if (fn.indexOf(miniprefix)!=-1){
  			fn = fn.substr(4);
  		}
    }
	}
  else {
  	if (is_default){
      fn = 'photothumb.jpg';
    }
    else {
      if (fn.indexOf(miniprefix)==-1){
        fn = miniprefix+fn;
      }
    }
  }
  
  if (!is_default){
  	fn += '?' + (new Date().getMilliseconds());
  }
  var result =filename.substr(0,i1) + '/' + fn + ')'; 
  
  //alert(filename+"\n"+result);
  
  return result;
}
*/
function save_order(src, dst){
	var h = $('wizard_v_photo_order');
  var s = h.value;
  var ds = "";
  
  for (var i=0;i<s.length;i++){
  	var c = s.charAt(i);
    if (c == src)      c = dst;
    else if (c == dst) c = src;
    ds+=c;
  }
  h.value=ds;
}

function delete_photo(pos) {
		var pic2 = $('picture'+pos+'bak');
		var pichidden = $('wizard_v_photo'+pos);

		pic2.style.backgroundImage = 'url('+contextPath + ((pos==1)?'/images/photothumbbig.gif':'/images/photothumb.jpg') +')';
		pichidden.value = '0';
		
	  // intercambio las imagenes.
	  new Ajax.Request(get_php_self(), {
	  	parameters:'action=deletepic&p='+pos, 
	  	onSuccess:function(request){
	  		// exelente.
	  	}});
}
