﻿//extends
Object.extend(Element, {
	getParentForm: function(element){
		element = $(element);
		while (element.tagName != "FORM"){
			element = element.parentNode;
		}
		return element;
	},

	block: function(element){
		element = $(element);
		element.style.display = "block";
	},
	
	visible: function(element){
		element = $(element);
		element.style.visibility = "visible";
	},
	
	hidden: function(element){
		element = $(element);
		element.style.visibility = "hidden";
	},

	niceRemove: function(element){
		element = $(element);
		var fader = new fx.FadeSize(element, {onComplete: function(){Element.remove(element);}});
		fader.toggle('height');
	},

	add: function(container, element, options){
		if (options && options.onBottom == true) {
			return container.appendChild(document.createElement(element));
		}
		else {
			return container.insertBefore(document.createElement(element), container.childNodes[0]);
		}
	}
});

Object.extend(Form, {
	empty: function(form){
		var elements = Form.getElements(form);
		
		for (var i=1;el=elements[i];i++){
			if (el.tagName.toLowerCase() == "textarea" || el.type == "text" || el.type == "password")
				el.value = "";
			if (el.type == "checkbox") { 
				el.checked = false;
				Element.removeClassName(el.parentNode, "oneChoiceSel");
			}
		}
	}
});

Object.extend(String.prototype, {
	urlyfy: function(){
		noChars = /\$|,|@|#|~|`|\*|\^|\(|\)|\[|\/|\]|\[|\}|\{|\;|\:|\'|\"|\<|\>|\?|\||\\|\!|\$/g;
		newVal = this.replace(noChars, "");
		s = newVal.replace(/\%/g,"-percent-");
		s = s.replace(/ /g,"-");
		s = s.replace(/\&/g,"-and-");
		s = s.replace(/\+/g,"-plus-");
		s = s.replace(/\=/g,"-equals-");
		s = s.toLowerCase();
		return s;
	}
});

//layout
var Layout = Class.create();
Layout.prototype = {
	initialize: function(changeSize, minSize, medSize, maxSize, cssStyle){
		this.medSize = medSize;
		this.changeSize = changeSize;
		this.minSize = minSize;
		this.maxSize = maxSize;
		this.cssStyle = cssStyle;
	},

	change: function(){
		var theWidth = this.getBrowserWidth();
		for (var i = 0; i < arguments.length; i++) {
			var element = $(arguments[i]);
			if (theWidth < this.changeSize) element.className = this.cssStyle;
			else element.className = "";
		}
	},

	constrain: function(el1, el2){
		el1 = $(el1);
		el2 = $(el2);
		var theWidth = this.getBrowserWidth();
		if (theWidth < this.minSize){
			el1.style.width = this.minSize -1 + "px";
			el2.style.width = this.minSize -12 + "px";
		}else if (theWidth > this.maxSize){
			el1.style.width = "100%";
			el2.style.width = this.maxSize - 18 + "px";
		}else {
			el1.style.width = "100%";
			el2.style.width = "98.5%";
		}
	},

	getBrowserWidth: function(){
		if (window.innerWidth) return window.innerWidth;
		else if (document.documentElement && document.documentElement.clientWidth != 0) return document.documentElement.clientWidth;
		else if (document.body) return document.body.clientWidth;
	}
};

//loaders
var Loader = Class.create();
Loader.prototype = {
	initialize: function(element, cssStyle, url, parameters, form, goodEnd){
	    this.element = element;
	    this.goodEnd = goodEnd || null;
		this.clearForm = form || null;
		this.url = url;
		this.parameters = parameters;
		this.loader = $(element);
		this.cssStyle = cssStyle;
		this.loader.fader = new fx.Opacity(this.loader, {duration: 100, onComplete: this.request.bind(this) });
		this.start();
	},
	
	start: function(){	    
		this.loader.className = 'loader';		
		this.loader.parentNode.className = this.cssStyle;
		this.loader.fader.custom(0.99, 0.2);
	},
	
	request: function(){
	   this.loader.fader.options.onComplete = this.reset.bind(this);
		new Ajax.Request(this.url, {method: 'post', postBody: this.parameters, onComplete: this.check.bind(this) });
	},
	
	check: function(request){	   
		var repVal = $('tabwrap').offsetHeight;
		var response = request.responseText;		
		/*var res = response.split("-__-");
		if(res.length == 2){
			var err_type = res[0];
			var err_msg = res[1];
			moo.writeMsg(err_msg, "error");
		}
		else{*/		
		    resultText = response.replace('tabwrap"', 'tabwrap" style="height:'+repVal+'px"');		    
    	    this.loader.innerHTML = resultText;    	    
    	    
    	    // eval the inner scripts
    	    while ((match = resultText.match(/<script[^>]*>(?!<\/script)([\w\W]*)<\/script[^>]*>/)))
    	    {
                eval(match[1]);
	            resultText = resultText.slice(match.lastIndex);
            }
			
			if (this.clearForm) Form.empty(this.clearForm);
			/*if (!this.goodEnd) moo.closeMsg();
			else if (this.goodEnd == true) moo.writeMsg('your item has been inserted successfully.', 'success');
			else if (this.goodEnd == 'deleted') moo.writeMsg('your item has been deleted successfully.', 'warning');*/
		//}			
		this.end();
	},

	reset: function(){
		this.loader.className = "";
		this.loader.parentNode.className = "";
	},

	end: function(){	    
	    Attitude.update(tableRules);
		this.loader.fader.custom(0.2, 0.99);
		//if (!this.adjust) this.adjust = new fx.Height($('tabwrap'), {duration: 300});
		//this.adjust.custom($('tabwrap').offsetHeight, $('tab').offsetHeight);
	}
};

var Addition = Class.create();
Addition.prototype = {
	setOptions: function(options) {
		this.options = {
			onComplete:	''
		},

		Object.extend(this.options, options || {});
	},

	initialize: function(element, html, container, options){
		container = $(container);
		this.setOptions(options);
		if (container.childNodes[0] && !this.options.onBottom)
			//var newElement = container.insertBefore(document.createElement(element), container.childNodes[0]);
			var newElement = Element.add(container, element, {onBottom : false});
		else
			//var newElement = container.appendChild(document.createElement(element));
			var newElement = Element.add(container, element, {onBottom : true});
		if (this.options.cssStyle) Element.addClassName(newElement, this.options.cssStyle);
		
		var fader = new fx.FadeSize(newElement, {duration: 400, onComplete: this.options.onComplete });
		fader.hide('height');
		newElement.innerHTML = html;
		fader.toggle('height');
	}
};

//livesearch
//function getFirstArticlePage()
function getEntityFirstPage(url,itemName)
{
    //var url = $F('articleListUrl');
	    /*var page = getURLPage(url);
	    var order = getURLParam('order', url)
	    var column = getURLParam('column', url)
	    var size = getURLParam('size', url)*/
	    
	    //doArticleFilters(page + "?column=" + column + "&order=" + order + "&index=1&size=" + size);	
	    doEntityFilters(setUrlParam(url, 'index', 1), itemName);	
}

//function doArticleFilters(url)
function doEntityFilters(url, itemName)
{
    //1.4.0 -ban működik a [] vagy new Array, 1.5.0-ben csak a {} vagy new object
    var element = 'loader';
    if (itemName!=null)
        element = itemName;
    else if ($('loader') == null)
        element = 'imageloader';
    
    var filter = {};
    if ($('caption')!=null)
        filter['caption'] = $F('caption');
        
    if ($('searchField')!=null)
        filter['searchField'] = $F('searchField');

    if ($('tags')!=null)
       filter['tags'] = $F('tags');
       
    if ($('columnFilter')!=null)
       filter['columnFilter'] = $F('columnFilter');

    new Loader(element, 'anim_load', url, ($H(filter)).toQueryString());  
}

var LiveSearch = Class.create();
LiveSearch.prototype = {
	setOptions: function(options) {
	this.options = {
      onComplete:   ''
	},
	Object.extend(this.options, options || {});
	},

	initialize: function(url, parameters, options)
	{
		this.setOptions(options);
		this.url = url;
		this.parameters = parameters;
		this.keys = new Array(2);
		this.timer = null;
	},

	chkKey: function()
	{
	    this.keys.push(this.key);
		if (this.keys[1] != this.keys[2]) 
		{
		    this.start();
        }
		this.keys.pop();
	},

	start: function(key)
	{
		if (key != null) 
		    this.key = key;
			
		 var url = $F(this.url);
         	         
         //getFirstArticlePage();		
         getEntityFirstPage(url);
	},

	setTimer: function(key)
	{
	    this.key = key;
		
		if (this.timer != null)
		{
			clearTimeout(this.timer);
		}
		this.timer = setTimeout(this.chkKey.bind(this), 500);
	}
};

var TagSearch = Class.create();
TagSearch.prototype = {
	setOptions: function(options) {
	this.options = {
      onComplete:   ''
	},
	Object.extend(this.options, options || {});
	},

	initialize: function(parameters, options)
	{
		this.setOptions(options);
		this.parameters = parameters;
		this.keys = new Array(2);
		this.timer = null;
	},

	chkKey: function()
	{
	    this.keys.push(this.key);
		if (this.keys[1] != this.keys[2]) 
		{
		    this.start();
        }
		this.keys.pop();
	},

	start: function(key)
	{
		if (key != null) 
		    this.key = key;
		    
		this.tagCursorPosition = getCaretPos(this.element);
		var textAtPosition = this.key.charAt(this.tagCursorPosition - 1);
		
		if (textAtPosition != ",")
		{
		    /*var first = 0;
    		
            if (this.key.indexOf(",") > -1 && this.key.indexOf(",") < cursorPosition)
            {
                first = this.key.indexOf(",");
            }	
            
            var textToSearch = this.key.substring(first, this.key.length - first)*/
            
            var first = getBeforeCommaPosition(this.key, this.tagCursorPosition);
            var last = getAfterCommaPosition(this.key, this.tagCursorPosition - 1);
            var toSearch = this.key.substring(first + 1, last);
            
            this.doTagSearch(toSearch,this.element.attributes['tagtype'].value);                           
        }
	},	
    
   	doTagSearch: function(text,tagType)
    {
        msgDiv = $("statusElement");  
        listDiv = $("auto_complete");
        
        if (trim(text) != "")           
        {
            if (msgDiv)
                msgDiv.innerHTML = "Cimke keresése...";
            
                if(tagType=='article')
                {
                    ArticleEdit.GetAllArticleTags
                    (
                        text,
                        this.OnProcess.bind(this)
                    );          
                }
                else
                {
                    ImageEdit.GetAllImageTags
                    (
                        text,
                        this.OnProcess.bind(this)
                    );     
                }
                
        } else {
            if (listDiv)
            {
                listDiv.innerHTML = "";
                listDiv.hide();
            }
            
            /* Hacking, must modify... */
            //if ($("articleListUrl"))
            if ($("listUrl"))
                onTagChanged();

        }
    },
     
    OnProcess: function(res) 
    {
        msgDiv = $("statusElement");  
        listDiv = $("auto_complete");
        
        if (res.error) 
        {
            if (msgDiv)
                msgDiv.innerHTML = res.error.Message;
            else
                alert(res.error.Message);   
        } else {
            if (msgDiv)
                msgDiv.innerHTML = "";
            
            if (listDiv && res.value.length > 0)
            {
                var html = "<ul id='tags'>";
                for (i = 0; i < res.value.length; i++)
                {
                    html += "<li class='tag'>" + res.value[i].Name + "</li>";
                }
                html += "</ul>";
                listDiv.innerHTML = html;
                
                //Add observers to the childs
                if (listDiv.firstChild && listDiv.firstChild.childNodes) 
                {
                    var entry_count = listDiv.firstChild.childNodes.length;
                    for (var i = 0; i < entry_count; i++) 
                    {
                        this.addObservers(listDiv.firstChild.childNodes[i]);
                    }
                 }
                
                listDiv.toggle();                                
            } else 
            {
                listDiv.innerHTML = "";
                listDiv.hide();
            }                                                            
        }
    },
    
    addObservers: function(element) 
	{
	    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
        Event.observe(element, "mouseout", this.onOut.bindAsEventListener(this));
        Event.observe(element, "click", this.onClick.bindAsEventListener(this));
    },
    
    onHover: function(event) 
    {
        var element = Event.findElement(event, 'LI');
        element.className = "selected";
        
        Event.stop(event);
    },
    
    onOut: function(event) 
    {
        var element = Event.findElement(event, 'LI');
        element.className = "tag";
        
        Event.stop(event);
    },
    
    onClick: function(event) 
    {
        var element = Event.findElement(event, 'LI');
         
        tagInput = $("tags");
        
	    var first = getBeforeCommaPosition(tagInput.value, this.tagCursorPosition);
        var last = getAfterCommaPosition(tagInput.value, this.tagCursorPosition - 1);
                        
        var pre = tagInput.value.substring(0 , first);
        var past = tagInput.value.substring(last);
            
        if (trim(pre) != "")
            pre += ", ";
        
        tagInput.value = pre + element.innerHTML + past;
        
        listDiv = $("auto_complete");
        if (listDiv)
            listDiv.hide();
        
        Event.stop(event);
        
        /* Hacking, must modify... */
        //if ($("articleListUrl"))
        if ($("listUrl"))
            onTagChanged();
    },

	setTimer: function(key, element)
	{
	    this.key = key;
	    this.element = element;
		
		if (this.timer != null)
		{
			clearTimeout(this.timer);
		}
		this.timer = setTimeout(this.chkKey.bind(this), 500);
	}
};  

function getBeforeCommaPosition(text, position)
{
    while (position-- > 0)
    {
        if (text.charAt(position) == ",")
        {
            break;
        }                
    }
    
    return position;
}

function getAfterCommaPosition(text, position)
{
    while (position++ < text.length)
    {
        if (text.charAt(position) == ",")
        {
            break;
        }                
    }
    
    return position;
}