// general functions

Array.prototype.min = function(){
	return Math.min.apply({},this)
}

Array.prototype.max = function(){
	return Math.max.apply({},this)
}


function searchSelect(input_id, select_id) {
	//var input = $(input_id).value;
	var output = $(select_id).options;
  	
  	$(input_id).observe('keyup', function(event) {
  		
	  	for(var i=0;i<output.length;i++) {

		    if(output[i].text.toLowerCase().indexOf($(input_id).value.toLowerCase()) >= 0){
		    	output[i].selected=true;
		     	 return;
		    }
		    if($(input_id).text==''){
		      output[0].selected=true;
		    }
	  	}
  	});
}

function isHidden(item_name) {
	if ($(item_name).style.display == "none")
		return true;
	else return false;
}

function toggleBlindItem(item_name) {
	var a_item = $(item_name);
	if (a_item.style.display=="none") {
		new Effect.BlindDown(item_name, {duration:0.2});
		return false;
	} else
	new Effect.BlindUp(item_name, {duration:0.2});
}

function replaceChars(a_string, out, add)
{
	//out = "a"; // replace this
	//add = "z"; // with this
	temp = "" + a_string; // temporary holder
	
	while (temp.indexOf(out)>-1)
	{
		pos= temp.indexOf(out);
		temp = "" + (temp.substring(0, pos) + add + temp.substring((pos + out.length), temp.length));
	}
	return temp;
}


function my_encodeURI(a_string)
{
	var string = a_string;
	//string = replaceChars(string, "#", "%23");
	string = encodeURI(string);
	//var i=0;
	//for (i=0;i<string.length;i++)
	//{
	//	if (string[i] == '&') string[i] = 
	//}
	string = replaceChars(string, "&", "%26");
	string = replaceChars(string, "?", "%3F");
	//string = replaceChars(string, "#", "%23");
	
	//string = replaceChars(string, "?", "%3F");
	//string = replaceChars(string, "?", "%3F");
	//string = replaceChars(string, "?", "%3F");
	
	//, / ? : @ & = + $ #
	
	return string;
}


function encode64(input)
{
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input)
{
   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}




function toggleWebDebugCCMessages(messages)
{
	var a_item = $('sfWebDebugCCMessages');
	if (a_item.style.display!="none")
	{
		a_item.hide();
		$('sfWebDebugCCMessages').innerHtml = '';
		return false;
	}
	
	web_debug_cc_messages_changes = $H();
	
	var parameters = messages.toQueryString();
	//alert(parameters);

	var ajax_params = new Object();
	ajax_params.parameters = parameters;
	ajax_params.evalScripts = true;
	ajax_params.onLoading = function()
		{
			$('sfWebDebugCCMessages').innerHtml = 'wait....';
		};
	
	//alert(ajax_params.inspect());
	var ajax = new Ajax.Updater('sfWebDebugCCMessages','/misc/getWebDebugCCMessageContent', ajax_params);
	
	
	sfWebDebugShowDetailsFor('sfWebDebugCCMessages');
	return false;
}





function webDebugCCMessagesOnSubmitCallback(a_event)
{

	var parameters = '';
	
	//alert(web_debug_cc_messages_changes.inspect());
	
	web_debug_cc_messages_changes.each(function (message_properties)
	{
		var message_id = message_properties[0];
		var message_langs = message_properties[1];
		
		var x = $H();
		
		message_langs.each(function (lang)
		{
			var lang_name = lang[0];
			var lang_changed = lang[1];
			
			if (lang_changed)
			{
				var a_val = $F('webdebug_cc_message_'+lang_name+'['+message_id+']');
				//alert(message_id+' '+a_val);
				//parameters.set('message_'+message_id+'_'+lang_name,encode64(a_val));
				if (a_val.length>0)
				{
					parameters += 'message_'+message_id+'_'+lang_name+'='+my_encodeURI(a_val)+'&';
				}
				else
				{
					parameters += 'message_'+message_id+'_'+lang_name+'&';
				}

			}
			//alert(message_id+' '+lang.inspect());
		});
	});
	
	//parameters = parameters.toQueryString();
	//alert(parameters);

	var ajax_params = new Object();
	ajax_params.parameters = parameters;
	ajax_params.evalScripts = true;
	ajax_params.onComplete = function(response)
		{
			//alert(response.responseText);
			//window.location.href = window.location.href;
		};
	
	//alert(ajax_params.inspect());
	var ajax = new Ajax.Request('/misc/setWebDebugCCMessages', ajax_params);
	//alert(1);
	
	return false;
}

function webDebugCCMessagesInputOnChangeCallback(message_id, lang)
{
	//alert('webDebugCCMessagesInputOnChangeCallback '+message_id);
	if (!web_debug_cc_messages_changes.get(message_id)) web_debug_cc_messages_changes.set(message_id, $H());
	web_debug_cc_messages_changes.get(message_id).set(lang, true);
	//alert(web_debug_cc_messages_changes.inspect());
}


function toggleWebDebugCCMessageInput(message_id, lang, class_name, make_wider)
{
	var input_id = 'webdebug_cc_message_'+lang+'['+message_id+']';
	//var container = $(input_id+'_container');
	var input = $(input_id);
	
	$$('.'+class_name).each(function(x)
	{
		//alert(x.inspect());
		if (make_wider)
		{
			x.style.width = '400px';
			x.style.height = '150px';
		}
		else
		{
			x.style.height = '40px';
			x.style.width = '400px';
		}
	});
	
	return false;
}

function reloadFullParcelInfo(id,temp){
	window.location.reload()
}


/* ******************************************************************
 i18n functions
****************************************************************** */

function stripStr(str) {
	return str.replace(/^\s*/, "").replace(/\s*$/, "");
}

// Multiline strip
function stripStrML(str) {
	// Split because m flag doesn't exist before JS1.5 and we need to
	// strip newlines anyway
	var parts = str.split('\n');
	for (var i=0; i<parts.length; i++)
		parts[i] = stripStr(parts[i]);

	// Don't join with empty strings, because it "concats" words
	return parts.join(" ");
}

// Return translation, if translation dictionary exists and has a translation.
function _(str) {
	if (i18nDict && i18nDict[str])
		return i18nDict[str];
	return str;
}

/* ******************************************************************
 Wyp object tools functions
****************************************************************** */

var Wyp = {
	

	init: function() {
		this.litboxes();
		this.init_responders();
	},
	
	litboxes: function() {	
		
		$$(".litbox-link").each(function(element) {			
			
			if(!element.hasClassName('observed')) {
			element.addClassName('observed');
			
			Event.observe(element,'click',function(event){
				str = element.readAttribute('rel');
				js_str = str.evalJSON();
				if(js_str.size != undefined) {
					dims = js_str.size.split('x');
					dim_w = dims[0];
					dim_h = dims[1];
				} else {
					dim_w = 640;
					dim_h = 400;
				}
			    Event.stop(event)
			    personal_litbox = new LITBox(js_str.href, {type:'iframe', 
			    	overlay:	true,draggable:false, height:dim_h, width:dim_w, resizable:false, opacity:1});
				});
			//	
			}		
			});//end each
	
	},
	
	limit_inputs: function(){
		 inputElements = $$('input.limited')
		 textareaElements = $$('textarea.limited')
		 
		 inputElements.each(function(i){
		 
		 })
		 
		 textareaElements.each(function(i){
		 	// do stuff
		 })
		 
	},
	
	countBreaklines: function(field) {
		var f = $(field);
		var count = 0;
		var index = f.value.indexOf('\n');
		while(index != -1) {
			count += 1;
			index = f.value.indexOf('\n',index+1);
    }
    return count;		
	},	
	
 	limitTextArea: function(tx, len){
		t = $(tx);
		var cid = "chars_for_"+tx;
		if(t.value == null) t.value = '';
		var temp = new Template('<input type="#{type}" id="#{id}" value="#{value}" class="#{cl}" disabled="disabled" style="width:25px" />');
		var show = {type: 'text', id: cid, value: len - t.value.length, cl: "chars-for-textarea"  };		

		new Insertion.After(tx, temp.evaluate(show));

 		Event.observe(tx, 'keyup', function(event){ 
			var c = Wyp.countBreaklines(tx);
			if(t.value.length > len) {
				if(event.keyCode == Event.KEY_BACKSPACE) {} 
  	 		else { 
					t.value = t.value.substring(0, len);
  	 			Event.stop(event);
 	 			} 
			} else{
				$(cid).value = len - t.value.length;	
			}  
  	});
		t.value = t.value.substring(0, len);
	},	
	
 	limitTextField: function(textfield, len){
		i = $(textfield);
		var iid = "chars_for_"+textfield;
		var temp = new Template('<input type="#{type}" id="#{id}" value="#{value}" class="#{cl}" disabled="disabled" style="width:25px" />');
		var show = {type: 'text', id: iid, value: len - i.value.length, cl: "chars-for-input"  };		
		new Insertion.After(textfield, temp.evaluate(show));
		
 		Event.observe(textfield, 'keyup', function(event){ 
			if(i.value.length > len) {
				if(event.keyCode == Event.KEY_BACKSPACE) {} 
  	 		else { 
					i.value = i.value.substring(0, len);
  	 			Event.stop(event);
 	 			} 
			} else{
				$(iid).value = len - i.value.length;	
			}  
  	});
		i.value = i.value.substring(0, len);
	},		
	
	init_responders: function() {
		
		Ajax.Responders.register({
		  onCreate: function() {
		  	if(!$('ajaxInteractive')){
			  	var ajaxInteractive = new Element('div',{'class':'ajax-interactive','id':'ajaxInteractive'})
					ajaxInteractive.update(new Element('span',{'class':'ajax-message','id':'ajaxMessage'}).insert(_('Loading...')))				
				  $$('body')[0].insert(ajaxInteractive)		  
				}
		  },
		  onComplete: function(xhr) {
			
			if(Ajax.activeRequestCount==0){
		  		$('ajaxInteractive').remove();
					Wyp.litboxes();
			}
		  	if(xhr.transport.status != 200 && xhr.transport.status != 0){
				//var xhrLitbox = new LITBox(_('Error while loading XHR request!'),{type:'alert',height:100,width:300})
		  	}		
		  }		
		});
				
	},
	
	countdown: function(year, month, day, hour, minute, lang){
		Today = new Date();
		Todays_Year = Today.getFullYear();
		Todays_Month = Today.getMonth();                  
					 
		//Convert both today's date and the target date into miliseconds.                           
		Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();                                 
		Target_Date = (new Date(year, month - 1, day, hour, minute, 00)).getTime();                  
		 
		//Find their difference, and convert that into seconds.                  
		Time_Left = Math.round((Target_Date - Todays_Date) / 1000);
		days = Math.floor(Time_Left / (60 * 60 * 24));
		
		Time_Left %= (60 * 60 * 24);
		hours = Math.floor(Time_Left / (60 * 60));
		
		Time_Left %= (60 * 60);
		minutes = Math.floor(Time_Left / 60);
		
		Time_Left %= 60;
		seconds = Time_Left;
		if(lang == 'en'){
			$('place-countdown').update(days + "D " + hours + "H " + minutes + "M " + seconds +"S")
		}	else{
			$('place-countdown').update(days + "T " + hours + "U " + minutes + "M " + seconds +"S")		
		}
		
               
  	//Recursive call, keeps the clock ticking.
  	if(day==0&&hour==0&&minute==0){
  		window.location.reload()
  		return true;
  	}else{
	  	setTimeout('Wyp.countdown(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute +',"' + lang +'");', 1000);		
  	}
  	
	},

	
	bookmarks: function(){
		$('social-bookmarks').insert('<span class="bookmark">Bookmark!</span>'		
+'<a href="http://www.linkarena.com/" onclick="window.open(\'http://linkarena.com/bookmarks/addlink/?url=\'+encodeURIComponent(location.href)+\'&amp;title=\'+encodeURIComponent(document.title)+\'&amp;desc=&amp;tags=\');return false;" title="Bookmark! Linkarena"><img src="/images/bookmarks/linkarena.gif" alt="Bookmark! Linkarena" name="Linkarena id="Linkarena"/></a>'
+'<a href="http://digg.com/" onclick="window.open(\'http://digg.com/submit?phase=2&amp;url=\'+encodeURIComponent(location.href)+\'&amp;bodytext=&amp;tags=&amp;title=\'+encodeURIComponent(document.title));return false;" title="Digg"><img src="/images/bookmarks/digg.gif" alt=" Digg" name="Digg" id="Digg"/></a>'
+'<a href="http://del.icio.us/" onclick="window.open(\'http://del.icio.us/post?v=2&amp;url=\'+encodeURIComponent(location.href)+\'&amp;notes=&amp;tags=&amp;title=\'+encodeURIComponent(document.title));return false;" title="Del.icio.us"><img src="/images/bookmarks/del.gif" alt=" Del.icio.us" name="Delicious" id="Delicious"/></a>'
+'<a href="http://www.mister-wong.de/" onclick="window.open(\'http://www.mister-wong.de/index.php?action=addurl&amp;bm_url=\'+encodeURIComponent(location.href)+\'&amp;bm_notice=&amp;bm_description=\'+encodeURIComponent(document.title)+\'&amp;bm_tags=\');return false;" title="Bookmark bei: Mr. Wong"><img src="http://www.social-bookmark-script.de/img/bookmarks/wong.gif" alt="Bookmark bei: Mr. Wong" name="wong" id="wong"></a>'
+'<a href="http://www.stumbleupon.com/" onclick="window.open(\'http://www.stumbleupon.com/submit?url=\'+encodeURIComponent(location.href)+\'&amp;title=\'+encodeURIComponent(document.title));return false;" title="Bookmark bei: StumbleUpon"><img src="http://www.social-bookmark-script.de/img/bookmarks/stumbleupon.gif" alt="Bookmark bei: StumbleUpon" name="StumbleUpon" border="0" id="StumbleUpon"> </a>'
+'<a href="http://alltagz.com"/ onclick="window.open(\'http://www.alltagz.de/bookmarks/?action=add&address=\+encodeURIComponent(location.href)+\'&amp;title=\'+encodeURIComponent(document.title));return false;" title="Bookmark bei: Alltagz"><img src="/images/bookmarks/alltagz.png" alt="Bookmark bei: Alltagz" style="border:1px solid #ccc"/></a>'
)	
}

}



/* ******************************************************************
 onload initializers
****************************************************************** */


document.observe("dom:loaded", function() {
	// init WYP object
	Wyp.init();

  $$('.confirm-box').each(function(item) {
  	
     	if(item.nodeName == "A") {
     		item.observe('click', function (event) {	  		
		  		event.stop();
		  		var blockUserConfirmation = new LITBox('Are you sure?', {type:'confirm', overlay:true, height:150, width:400, opacity:1, func: function(){
						 f = document.createElement('form'); 
						 document.body.appendChild(f); 
						 f.method = 'post'; 
						 f.action = item.href; 
						 f.submit()
				}});	
			});
     	} else if(item.nodeName == "FORM") {
     		item.observe('submit', function (event) {  		
		  		event.stop();
		  		var blockUserConfirmation = new LITBox('Are you sure?', {type:'confirm', overlay:true, height:150, width:400, opacity:1, func: function(){
						 item.submit();
				}});	
			});
     	}
	}) 
});


