var CurrentAjaxSearch = "";
/*
onsubmit = function()
{
	alert('hello'+CurrentAjaxSearch);
	return false;
}*/

FormValidate = function(name) {
  var FieldsToCheck = document.forms[name].elements;
  return FormCheckRequired(FieldsToCheck);
}

FormCheckRequired = function(FieldsToCheck)
{
  var talert="";
  var label ="";
  var divitem   ="";
  for (var i=0; i < FieldsToCheck.length; i++){
     if(FieldsToCheck.item(i).className.indexOf('require') != -1) {
         if(!FieldsToCheck.item(i).value ||
             FieldsToCheck.item(i).type == 'select-one' && !FieldsToCheck.item(i).item(0) ||
             FieldsToCheck.item(i).type == 'select-multiple' && !FieldsToCheck.item(i).item(0)
             ) {
                label  = document.getElementById(FieldsToCheck.item(i).id + "_l");
                divitem= document.getElementById(FieldsToCheck.item(i).id + "_d");
                divitem.className   = divitem.className + " error_row";
                label.className = label.className + " error_label";
                talert = talert+"  - "+label.innerHTML+"\n";
         }
     }
  }

  if(talert) {
    talert = "You need to complete the following required fields: \n"+talert;
    alert(talert);
    return false;
  }
  return true;
}
var ParentWindow = "";
GetIframeHeight = function(id)
{
    if(id.substr(0,6) == 'widget') {
        if(id && $(id) && $(id).document) {
            //return $(id).document.body.scrollHeight;
        } else if(id && frames[id] && frames[id].document) {
            return(frames[id].document.body.scrollHeight);
        }
    }
}

ResizeIframe = function(id)
{
    if(document.getElementById(id)) {
        height = GetIframeHeight(id);
        if(height > 0){
            document.getElementById(id).style.height = height+40+"px";
        }
    }
}

FormToggleTab = function(hprefix,cprefix,aprefix,number) {

    var counter  = 1;
    var tabHeight= 0;
    var height   = 0;
    var area     = $(aprefix);
    var content  = $(cprefix+number);
    var tab      = $(hprefix+number);

    if(tab.className == "widget_tab first" || tab.className == "widget_tab first_selected") {
        tab.className = 'widget_tab first_selected';
    } else if(tab.className == "widget_tab last" || tab.className == "widget_tab last_selected") {
        tab.className = 'widget_tab last_selected';
    } else {
        tab.className = 'widget_tab selected';
    }
    var f = content.getElementsByTagName('iframe');

    $(cprefix+number).style.display = 'block';
    for(fs=0;fs < f.length;fs++) ResizeIframe(f[fs].id);
    if(parent && ParentWindow) parent.ResizeIframe(ParentWindow);
    $(cprefix+number).style.display = 'block';

    //Effect.toggle(cprefix+number,'appear',{duration:0.1});

    while(tab = $(hprefix+counter)) {
        content = $(cprefix+counter);
        if(counter != number) {

            if(tab.className == "widget_tab first_selected" || tab.className == "widget_tab first") {
                tab.className = 'widget_tab first';
            } else if(tab.className == "widget_tab last_selected" || tab.className == "widget_tab last") {
                tab.className = 'widget_tab last';
            } else {
                tab.className = 'widget_tab';
            }

            content.style.display = 'none';
        }
        counter++;
    }

    if(parent && ParentWindow) setTimeout("parent.ResizeIframe('"+ParentWindow+"')",300);
    if(parent && ParentWindow) setTimeout("parent.ResizeIframe('"+ParentWindow+"')",600);

}

var w;
SmallWindow = function(name,url)
{
	var nstr = name;
    nstr = nstr.replace(" ","");
    w = window.open(url, nstr, 'width=840,height=700,scrollbars=yes,resizable=yes,directories=no,toolbar=no,menubar=no,status=no');
    return true;
}

OpenWindow = function(url, name, width, height, toolbar, menubar, status, location)
{
	var nstr = name;
    nstr = nstr.replace(" ","");
    w = window.open(url, nstr, 'width=' + width + ',height=' + height + ',scrollbars=yes,resizable=yes,directories=no,toolbar='+toolbar+',menubar='+menubar+',status='+status+',location='+location);
    w.moveTo(200,200);
}

AjaxListTrigger = function()
{

}

ListClickBack = function(field,id,namefield)
{
    var Ids    = opener.document.getElementById(field).value;
    var IdArr  = Ids.split(",");
    var exists = false;
    var count  = 0;
    var current= 0;
    var NewIdArr  = new Array();
    var newhref   = window.location;
    if(!IdArr || !IdArr[0]) {
        IdArr = new Array();
    }

    while(current = IdArr[count]) {
        if(!IdArr[count]) break;
        if (current == id) {
            exists = true;
            break;
        }
        count++;
    }

    if(exists) {
        setTimeout("opener."+field+"_class."+'RemoveChildById('+id+')',0);
    } else {
        setTimeout("opener."+field+"_class."+'AddChild("'+id+'","'+id+' - '+namefield+'")',0);
    }

    setTimeout("LickClickHighlight('"+field+"');",0);
}

LickClickHighlight = function(field)
{
    var Ids;
    if(opener && opener.document.getElementById(field)) {
        Ids = opener.document.getElementById(field).value;
        var IdArr  = Ids.split(",");

        var count = 0;
        var Current = window.document.getElementsByTagName('tr');
        while(current = Current[count]) {
            if(current.className == 'selected_row') current.className = '';
            count++;
        }

        count=0;
        if(IdArr.length) {
            while(current = IdArr[count]) {
                field = $('listrow_'+current);
                if(field) {
                    field.className = 'selected_row';
                }
                count++;
            }
        }
    }
}

HighlightRow = function(row)
{
    var IdArr = row.split(",");
    var count = 0;
    var Current = document.getElementsByTagName('tr');
    while(current = Current[count]) {
        if(current.className == 'selected_row') current.className = '';
        count++;
    }

    count=0;
    if(IdArr.length) {
        while(current = IdArr[count]) {
            field = $('listrow_'+current);
            if(field) {
                field.className = 'selected_row';
            }
            count++;
        }
    }
}


DeleteConfirm = function()
{
    return confirm("Are you sure you wish to delete?");
}


var MuonMultiSelect = Class.create();
MuonMultiSelect.prototype = {
	initialize: function(Id, Name, Url, Multi, InitData) {
	   this.Container = $(Id+'_div');
	   this.Data      = InitData;
	   this.Id        = Id;
	   this.Name      = Name;
	   this.Url       = Url;
	   this.CallOut   = 0;
	   this.Child     = new Array();
	   this.NumberItems=0;
	   this.Counter   = 0;
	   this.Multi     = 0;
	   var count      = 0;
	   if(Multi) this.Multi = true;

	   this.BuildChildren();
	   this.UpdateInput();
	},
	UpdateInput: function() {
	   this.Container.Input.value = "";
	   var self = this;
	   this.Child.each( function(child){
	           if(child && child.Value) {
	               if(self.Container.Input.value) self.Container.Input.value += ",";
                    self.Container.Input.value += child.Value;
	           }
	       });
	   if(this.CallOut) {
	       eval("if(typeof "+this.CallOut+" == 'function') "+this.CallOut+"();");
	   }
	},
	RemoveChild: function(Position) {
	   this.Data[Position] = true;
	   this.BuildChildren();
	   this.UpdateInput();

        if(this.NumberItems < 1) {
            this.AddNewChild();
        }
	},
	RemoveChildById: function(id) {
	   var count = 0;
	   while(this.Data[count]) {
	       if(this.Data[count]['id'] && this.Data[count]['id'] == id) {
	           this.RemoveChild(count);
	           break;
	       }
	       count++;
	   }
	},
	BuildChildren: function() {
	   var count = 0;
	   this.Container.innerHTML = "";

	   if(this.Multi) {
       this.Container.AddMore = document.createElement('div');
       this.Container.AddMore.id = this.Id+'_add_more';
       this.Container.AddMore.className = 'window_item_add';
       this.Container.appendChild(this.Container.AddMore);
       Event.observe(this.Container.AddMore,'click',this.AddNewChild.bindAsEventListener(this));
	   }

       this.Container.ShowList = document.createElement('input');
       this.Container.ShowList.type = 'button';
       this.Container.ShowList.value = '...';
       this.Container.ShowList.id = this.Id+'_show_list';
       this.Container.ShowList.className = 'window_item_list';
       this.Container.appendChild(this.Container.ShowList);
       var c = this.Id+'_window';
       Event.observe(this.Container.ShowList,'click',function(){setTimeout(c+"();",10)});

       this.Container.Input = document.createElement('input');
       this.Container.Input.name = this.Name;
       this.Container.Input.id = this.Id;
       this.Container.Input.type = 'hidden';
       this.Container.appendChild(this.Container.Input);
	   this.Child = new Array();
	   this.NumberItems = 0;
	   this.Counter = 0;
	   while(this.Data[this.Counter]) {
	       if(this.Data[this.Counter]['id'] || this.Data[this.Counter]['new']){

	           this.Child[this.Counter] = new MuonMultiSelectChild(this, this.Counter, this.Id+'_'+this.Data[this.Counter]['id'], this.Id+'_'+this.Counter+'_pass', this.Data[this.Counter]['name'], this.Data[this.Counter]['id'], this.Url);

	           this.NumberItems++;
	       }
	       this.Counter++;
	   }

	},
	AddNewChild: function()
	{
	    if(!this.Multi) {
	       this.Counter = 0;
	    }
	    this.Data[this.Counter] = new Array();
	    this.Data[this.Counter]['new'] = true;
	    this.Data[this.Counter]['id'] = "";
	    this.Data[this.Counter]['name'] = "";
	    this.BuildChildren();
	    this.UpdateInput();
	},
	AddChild: function(id,name)
	{
	    if(!this.Multi) {
	       this.Counter = 0;
	    }
	    this.Data[this.Counter] = new Array();
	    this.Data[this.Counter]['id'] = id;
	    this.Data[this.Counter]['name'] = name;
	    this.BuildChildren();
	    this.UpdateInput();
	}
}


var MuonMultiSelectChild = Class.create();
MuonMultiSelectChild.prototype = {
	initialize: function(Parent, Position, Id, Name, DisplayName, Value, Url) {
	   this.Parent     = Parent;
	   this.Position   = Position;
	   this.Id         = Id;
	   this.Container  = false;
	   this.ElementName=Name;
	   this.Name       =DisplayName;
	   this.Value      =Value;
	   this.Url        =Url;
	   this.CreateMe();
	},
	CreateMe: function()
	{
        this.Container = document.createElement('div');
        this.Container.id = this.Id+'_container';
        this.Container.Input = document.createElement('input');
        this.Container.Input.name = this.ElementName;
        this.Container.Input.className = 'window_form_field';
        this.Container.Input.type = 'text';
        this.Container.Input.id = this.Id;
        this.Container.Input.value = this.Name;
        this.Container.Dropper = document.createElement('div');
        this.Container.Dropper.id  = this.Id+'_dropper';
        this.Container.Dropper.className = 'autocomplete';
        this.Container.Dropper.innerHTML = ' ';
        this.Container.DropDown = document.createElement('div');
        this.Container.DropDown.className = 'window_item_dropdown';
        this.Container.DropDown.innerHTML = ' ';
        this.Container.DropDown.id  = this.Id+'_dropit';

        this.Container.appendChild(this.Container.Input);
        this.Container.appendChild(this.Container.Dropper);
        this.Container.appendChild(this.Container.DropDown);

        this.Container.Remove = document.createElement('div');
        this.Container.Remove.className = 'window_item_delete';
        this.Container.Remove.id  = this.Id+'_remove';
        this.Container.Remove.innerHTML = ' ';
        this.Container.appendChild(this.Container.Remove);
        Event.observe(this.Container.Remove,'click',this.Remove.bindAsEventListener(this));

        Event.observe(this.Container.Input,'change',this.OnChange.bindAsEventListener(this));
        Event.observe(this.Container.Input,'focus',this.OnFocus.bindAsEventListener(this));
        Event.observe(this.Container.DropDown,'click',this.DropIt.bindAsEventListener(this));

        this.Parent.Container.appendChild(this.Container);
	    this.Autocomplete           = new Ajax.Autocompleter(this.Id,this.Id+'_dropper', this.Url, {frequency:0.1,afterUpdateElement:this.OnChange.bindAsEventListener(this),minChars:0});

	},
	OnChange: function()
	{
	   Ida = this.Container.Input.value.split('-');
	   this.Value = Ida[0];
	   this.Value = this.Value.replace(' ','');
	   if(this.Value * 1 != this.Value) {
           this.Container.Input.value = this.Parent.Data[this.Position]['name'];
	       this.Container.Input.focus();
	       this.Container.Input.select();
	   } else {
	       this.Parent.Data[this.Position]['id'] = this.Value;
	       this.Parent.Data[this.Position]['name'] = this.Container.Input.value;
	       this.Parent.UpdateInput();
	   }
	},

	OnFocus: function()
	{
	    this.Container.Input.select();
	},

	Remove: function()
	{
        this.Parent.Container.removeChild(this.Container);
        this.Parent.RemoveChild(this.Position);

        if(this.Parent.NumberItems < 1) {
            this.Parent.AddNewChild();
        }
	},
	DropIt: function()
	{
	    this.Container.Input.blur();
	    this.Name = this.Container.Input.value;
	    this.Container.Input.value = "";
	    var self = this;
	    setTimeout(function(){ self.Autocomplete.activate();}, 10);
        setTimeout(function(){ self.Container.Input.value = self.Name;self.Container.Input.select();}, 10);
	}
}

AjaxLoad = function (id,url)
{
    new Ajax.Updater(id, url, {method:'get',parameters:'',asynchronous:false,evalScripts:true});
}

NewArea = function (id)
{
    $('window_area').innerHTML = $('window_area').innerHTML + '<div id="'+id+'" style="position:absolute;z-index:1000;width:99%;margin-left:100px"></div>';
}

onfocus = function()
{
    if(w && w.open && !w.closed) w.close();
}

onunload = function()
{
    if(w && w.open && !w.closed) w.close();
}

function insertAtCaret(obj, text) {
        if(document.selection) {
            obj.focus();
            var orig = obj.value.replace(/\r\n/g, "\n");
            var range = document.selection.createRange();

            if(range.parentElement() != obj) {
                return false;
            }

            range.text = text;

            var actual = tmp = obj.value.replace(/\r\n/g, "\n");

            for(var diff = 0; diff < orig.length; diff++) {
                if(orig.charAt(diff) != actual.charAt(diff)) break;
            }

            for(var index = 0, start = 0;
                tmp.match(text)
                    && (tmp = tmp.replace(text, ""))
                    && index <= diff;
                index = start + text.length
            ) {
                start = actual.indexOf(text, index);
            }
        } else if(obj.selectionStart) {
            var start = obj.selectionStart;
            var end   = obj.selectionEnd;

            obj.value = obj.value.substr(0, start)
                + text
                + obj.value.substr(end, obj.value.length);
        }

        if(start != null) {
            setCaretTo(obj, start + text.length);
        } else {
            obj.value += text;
        }
}

function setCaretTo(obj, pos) {
        if(obj.createTextRange) {
            var range = obj.createTextRange();
            range.move('character', pos);
            range.select();
        } else if(obj.selectionStart) {
            obj.focus();
            obj.setSelectionRange(pos, pos);
        }
}
