var FormWatch4 = Class.create();
FormWatch4.prototype = {
   initialize : function(form, options) {
      this.submitted = false;
      this.form = $(form);
      this.formcontents = $(form).serialize();
      Event.observe(this.form, 'submit', function() {this.submitted = true; }.bind(this));
      Event.observe(window, 'beforeunload', this.confirmExit.bind(this));
   },
   confirmExit : function(ev) {
      this.newcontents = this.form.serialize();
      if ((this.formcontents != this.newcontents) && !(this.submitted)) {
         ev.returnValue = warningMessage;
      }
   }
}
function createSort()
{
	Sortable.create('stepsSort', {onUpdate:function(){new Ajax.Updater('feedback', '/kuidas/web/profile/article/write/id/sort/', {asynchronous:true, evalScripts:true, onComplete:function(request, json){ReNumber()}, parameters:Sortable.serialize('stepsSort')})}, only:'sortable'})
}
function addItem()
{
	var last_step = $('stepsSort').select('li').last();
	var array     = $('stepsSort').select('li');
	var stepArray = $A(array);
	var max       = [];
	var temp;
	var newId;
	stepArray.each(function(stepArray){
		newId  = stepArray.id.sub('step_', '');
    temp   = parseInt(newId.sub(/_\d+/, ''));
		max.push(temp);
	});
	var length 	= parseInt(max.max());

	var step 		= $('step_add').cloneNode(true);

	step.getElementsByTagName('label')[0].id 			= 'divstep_'+(length+1);
	step.getElementsByTagName('textarea')[0].id 	= 'article_step_'+(length+1);
	step.getElementsByTagName('textarea')[0].name = 'article[step]['+(length+1)+']';
	step.getElementsByTagName('a')[1].className 	= 'step_'+(length+1);
	step.getElementsByTagName('a')[1].id 					= 'divstep_id_'+(length+1);

	step.getElementsByTagName('input')[0].id 			= 'step_image_'+(length+1);
	step.getElementsByTagName('input')[0].name 		= 'step_image_'+(length+1);
	step.getElementsByTagName('input')[1].id 			= 'step_image_title_'+(length+1);
	step.getElementsByTagName('a')[2].setAttribute("onclick", "$('step_image_"+(length+1)+"').show(); this.hide(); return false;");
	step.getElementsByTagName('div')[0].id = 'error_for_article_step_'+(length+1);
	step.getElementsByTagName('div')[1].id = 'step_image_'+(length+1);

  step.getElementsByTagName('img')[0].setAttribute("onclick", "addtag('article_step_"+(length+1)+"', 'b')");
  step.getElementsByTagName('img')[1].setAttribute("onclick", "addtag('article_step_"+(length+1)+"', 'i')");
  step.getElementsByTagName('img')[2].setAttribute("onclick", "addtag('article_step_"+(length+1)+"', 'u')");
  step.getElementsByTagName('img')[3].setAttribute("onclick", "addurltag('article_step_"+(length+1)+"')");
  step.getElementsByTagName('img')[4].setAttribute("onclick", "addtag('article_step_"+(length+1)+"', 'code')");

	var toInsertHtml = '<li class="sortable" id="step_'+(length+1)+'">'+step.innerHTML+'</li>';
	$('stepsSort').insert({bottom: toInsertHtml});
 
	ReNumber();
	initForm();
	createSort();
}
function ReNumber()
{
	var i = 0;	
	$A(document.getElementsByClassName('sortable')).each(
		function(li) {
			i++;
			li.getElementsByTagName('label')[0].innerHTML = 'Samm ' + i + ': ';
		}
	);
}
function removeItem(step, msg)
{
  var counter = 0; 
  $('stepsSort').select('li[class="sortable error"]', 'li[class=sortable]').each(function(element){
    counter++;
  });
  
  if (counter == 3)
  {
    alert("Artikkel peab sisaldama vähemalt 3 sammu");
    return;
  }
	if(!msg)
	{
		var msg = "Oled kindel, et tahad seda sammu kustutada?";
	}
	if (!confirm(msg))
  return;
	$(step).remove();
	ReNumber();
}
function addStars(e, element)
{
	var key;
	if(window.event) {
		key = e.keyCode; 
	}
	else if(e.which) {
		key = e.which; 
	}
	else {
		return true;
	}
	if (key == '13')
	{
    CreateStars(element);
	}
}
function CreateStars(element)
{
  var theText = element.value;

  theText = theText.replace(new RegExp("\\r", "g"), "");
  theText = theText.replace(new RegExp("\\n\\*  ", "g"), "*");
  theText = theText.replace(new RegExp("\\*  ", "g"), "*");
  theText = theText.replace(new RegExp("\\n", "g"), "*");
  theText = theText.replace(new RegExp("\\*", "g"), "\n*  ");
  theText = theText.replace('\r', '');
  theText = theText.replace('\n', '');
  
  element.value = theText;
}
function ReplaceAll(Str, Replace, ReplaceWith)
{
  //alert(Str);
  while (Str.indexOf(Replace) > 0)
  {
      Str = Str.replace(Replace, ReplaceWith);
  }
  //alert(Str);
  return Str;
}
function ismaxlength(obj)
{
    var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
    if (obj.getAttribute && obj.value.length>mlength)
        obj.value=obj.value.substring(0,mlength);
}
function removeAllOptions(selectbox)
{
  var i;
  for(i=selectbox.options.length-1;i>=0;i--)
  {
    selectbox.remove(i);
  }
  //selectbox.innerHTML = '';
}
function addOption(selectbox, value, text)
{
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;

    selectbox.options.add(optn);
}
function addCategory()
{
  var Cat       = document.getElementById('article_maincategory');
  var SubCat    = document.getElementById('article_sub1');
  var SubSubCat = document.getElementById('article_sub2');
  var text      = catFirstNode;
  var removeText= catRemoveNode;
  var CatValueNR;
  var length;
  var lastId;
  
  var array     = $('categories').getElementsByClassName('categoryClass');
	var catArray  = $A(array);
	var max       = [];
	var temp;
	var stop      = false;

	length 	= parseInt(catArray.length);
	var lastElement = catArray.last();
	if(lastElement)
	{
    temp = lastElement.id.split("_");
    lastId = parseInt(temp[1]);
  }
  if(!lastId)
  {
    lastId = 0;
  }
	if(!length)
	{
    length = 0;
  }
  if (length > 4)
  {
    return;
  }
    
  if (Cat.selectedIndex != -1)
  {
    text = text + ' &#187; ' + Cat.options[Cat.selectedIndex].innerHTML;
    CatValueNR = Cat.value;
  } else {
    alert(categoryError);
    return;
  }
  if (SubCat.selectedIndex != -1)
  {
    text = text + ' &#187; ' + SubCat.options[SubCat.selectedIndex].innerHTML;
    CatValueNR = SubCat.value;
  } else {
    alert(categoryError);
    return;
  }
  
  if (SubSubCat.selectedIndex != -1)
  {
    text = text + ' &#187; ' + SubSubCat.options[SubSubCat.selectedIndex].innerHTML;
    CatValueNR = SubSubCat.value;
  } else {
    alert(categoryError);
    return;
  }
  
    $$('#categories input[type=hidden]').each(function(element){
      if(parseInt(CatValueNR) == parseInt($(element).getValue()))
      {
       stop = true;
      }
    });
  if(stop)
  {
    return;
  }
  var CatDiv = document.createElement("div");
  CatDiv.setAttribute("id", "cat_" + (lastId+1));
  CatDiv.setAttribute("class", "categoryClass");
  
  var RemoveHref = document.createElement("a");
  RemoveHref.setAttribute("href", "#");
  RemoveHref.onclick = function(){RemoveCat((lastId+1)); return false;};
  RemoveHref.innerHTML = removeText;
  
  var CatValue = document.createElement("input");
  CatValue.setAttribute("type", "hidden");
  CatValue.setAttribute("id", "Category_" + (lastId+1));
  CatValue.setAttribute("name", "Category[" + (lastId+1) + "]");
  CatValue.setAttribute("value", parseInt(CatValueNR));
  
  CatDiv.innerHTML = text;
  CatDiv.appendChild(document.createTextNode(' | '));
  CatDiv.appendChild(RemoveHref);
  CatDiv.appendChild(CatValue);
  
  var Categories = document.getElementById('categories');
  Categories.appendChild(CatDiv); 
}
function RemoveCat(cat_id)
{
  $('cat_' + cat_id).remove();
}
function addtag(id, tag) {
	var txt = document.getElementById(id);

	if(document.selection) {
		txt.focus();
		sel = document.selection.createRange();
		sel.text = '[' + tag + ']' + sel.text + '[/' + tag + ']';
	} else if(txt.selectionStart || txt.selectionStart == '0') {	
		txt.value = (txt.value).substring(0, txt.selectionStart) + "["+tag+"]" + (txt.value).substring(txt.selectionStart, txt.selectionEnd) + "[/"+tag+"]" + (txt.value).substring(txt.selectionEnd, txt.textLength);
	} else {
		txt.value = '[' + tag + '][/' + tag + ']';
	}
	return;
}
function addurltag(id) {
	var txt = document.getElementById(id);
	var link = prompt(addAddressText, "http://");
	if(typeof(link) == 'object'){link = '';}
	if(link.length == 0 || link == "http://") {
		return;
	} else {
		var link = "=" + link;
		var text;
		var sel2 = "";
		if(document.selection) {
			txt.focus();
			sel = document.selection.createRange();
			sel2 = sel.text;
		} else if(txt.selectionStart || txt.selectionStart == '0') {
			sel2 = (txt.value).substring(txt.selectionStart, txt.selectionEnd);
		}
		if(sel2.length > 0) {
			text = sel2;
		} else {
			text = prompt(addLinkText, "");
		}
	}
	if(document.selection) {
		txt.focus();
		sel = document.selection.createRange();
		sel.text = "[url" + link + "]" + text + "[/url]";
	} else {
		txt.value = (txt.value).substring(0, txt.selectionStart) + "[url" + link + "]" + text + "[/url]" + (txt.value).substring(txt.selectionEnd, txt.textLength);
	}
	return;
}
var Overlay = Class.create();
Overlay.prototype = {
  initialize: function (content, container, form)
  {
    // Manage arguments and assign defaults,
  	if (typeof container == 'undefined' ) container = document.body;
  	if (null == (this.container = $(container))) throw("container is not valid");
  	if (form != 'null' && typeof(form) == 'undefined') {
  	 throw ("No form name specified");
  	}
   
  	// Assign instance variables
  	this.content = content;
  	this.form    = form;
  	this.overlay = new Element('div', { 'class': 'overlay' }).hide();
  	this.dialog  = new Element('div', { 'class': 'dialog' }).hide();
   
  	// Hide the overlay when clicked. Ignore clicks on the dialog.
  	//Event.observe(this.overlay, 'click', this.hide.bindAsEventListener(this));
  	Event.observe(this.dialog, 'click',  function(event) { Event.stop(event) });
   
  	// Insert the elements into the DOM
  	this.dialog.insert(this.content);
  	this.container.insert(this.overlay);
    this.container.insert(this.dialog);
   
  	// Content may have been hidden if it is embedded in the page
  	content.show();
  	this.dialog.hide();
  	if (form != 'null')
  	{
  	 Event.observe(this.form, 'submit', this.show.bind(this));
    }
  },
  show: function()
  {
    new Effect.Appear(this.overlay, { duration: 0.5,  to: 0.8 });
	  this.dialog.show();
	  return this;
  },
  hide: function()
  {
    this.dialog.hide();
	  this.overlay.hide();
	  return this;
  }
}
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	
		  string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};

var ResizingTextArea = Class.create();

ResizingTextArea.prototype = {
    defaultRows: 1,

    initialize: function(field)
    {
        this.defaultRows = Math.max(field.rows, 1);
        this.resizeNeeded = this.resizeNeeded.bindAsEventListener(this);
        Event.observe(field, "click", this.resizeNeeded);
        Event.observe(field, "keyup", this.resizeNeeded);
    },

    resizeNeeded: function(event)
    {
        var t = Event.element(event);
        var lines = t.value.split('\n');
        var newRows = lines.length + 1;
        var oldRows = t.rows;
        for (var i = 0; i < lines.length; i++)
        {
            var line = lines[i];
            if (line.length >= t.cols) newRows += Math.floor(line.length / t.cols);
        }
        if (newRows > t.rows) t.rows = newRows;
        if (newRows < t.rows) t.rows = Math.max(this.defaultRows, newRows);
    }
}

