String.prototype.trim = function() { return this.replace(/ {2,}/g,' ').replace(/[\n\r]*/g,''); };
Array.prototype.inArray = function (value) { var i; for (i=0; i < this.length; i++) { if (this[i] === value) { return true; } } return false; };

var Webadmin = {}
//
Webadmin.Cookie = function(){
    return {
        /*
         * Sets a named cookie
         *
         * @param {String} name The name of the cookie.
         * @param {String} value The value of the cookie.
         * @param {Int} expires The number of days in which the cookie will expire.
         * @param {String} path The path in which the cookie will be valid.
         * @param {String} domain The domain in which the cookie will be valid.
         * @param {Bool} secure Whether this is a secure cookie.
         */
        set : function(name, value, expires, path, domain, secure) {
            var today = new Date();
            today.setTime( today.getTime() );
            if (expires) expires = expires * 1000 * 60 * 60 * 24;
            var expires_date = new Date( today.getTime() + (expires) );
            document.cookie = name + "=" +escape(value) +
            ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
        },
        /*
         * Gets a named cookie
         *
         * @param {String} name The name of the cookie to get.
         * @return {String} The value of the cookie.
         */
        get : function(name) {
            var start = document.cookie.indexOf( name + "=" );
            var len = start + name.length + 1;
            if((!start)&&(name != document.cookie.substring(0, name.length))){
                return null;
            }
            if(start == -1) return null;
            var end = document.cookie.indexOf( ";", len);
            if(end == -1) end = document.cookie.length;
            return unescape(document.cookie.substring(len, end));
        },
        /*
         * Destroys a named cookie
         *
         * @param {String} name The name of the cookie to destroy.
         * @param {String} path The path of the cookie to destory.
         * @param {String} domain The domain of the cookie to destory.
         */
        destroy : function(name, path, domain) {
            if (getCookie(name)) document.cookie = name + "=" +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
        }
    }
}();
//
Webadmin.ListFilter = Class.create();
Webadmin.ListFilter.prototype = {
    initialize : function(input, list, options) {
      this.options = Object.extend({
      }, options || {});
      this.input = $(input);
      this.list = $(list);
      this.entries = new Array;
      var items = this.list.getElementsByTagName('li');
      var length = items.length;
        for (var i=0; i < length; i++) {
          if(items[i].textContent) var content = items[i].textContent;
          if(items[i].innerText) var content = items[i].innerText;
        var entry = new Array(items[i].id, content.trim(), items[i].innerHTML);
        this.entries.push(entry);
        }
      this.setup();
  },
  setup : function(){
      this.keyUpListener = this.keyUpEvent.bindAsEventListener(this);
      //Event.observe(this.input, 'keyup', this.keyUpListener);
      new Form.Element.Observer(this.input, 1, this.keyUpListener);
  },
  keyUpEvent : function(value){
    var value = $F(this.input);
    if(value!=""){
        this.filter(value);
    }else{
        this.render(this.entries);
    }
  },
  filter : function(value) {
      var regex = eval("/^"+value.toLowerCase()+"/");
      var newEntries = new Array;
      for (var i=0; i < this.entries.length; i++) {
            var value = new String(this.entries[i][1].toLowerCase());
      if(regex.test(value)){
          newEntries.push(this.entries[i]);
      }
      }
      this.render(newEntries);
  },
  render : function(entries){
    var markup = new Array;
    for (var i=0; i < entries.length; i++) {
        markup.push('<li id="'+entries[i][0]+'">'+entries[i][2]+'</li>');
    }
    this.list.innerHTML = markup.join('');
  }
}
//
Webadmin.Window = {
    getHeight: function(){
        var windowHeight;
        if (self.innerHeight) {    // all except IE
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // IE 6 Strict Mode
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other IEs
            windowHeight = document.body.clientHeight;
        }
        return windowHeight;
    },
    getWidth: function(){
        var windowWidth;
        if (self.innerWidth) {    // all except IE
            windowWidth = self.innerWidth;
        } else if (document.documentElement && document.documentElement.clientWidth) { // IE 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
        } else if (document.body) { // other IEs
            windowHeight = document.body.clientWidth;
        }
        return windowWidth;
    }
}
//
//Webadmin.Login = {
//    initialize : function(){
//        this.content = $('w-login-wrapper');
//        Event.observe(window, 'resize', this.setDimensions.bindAsEventListener(this));
//        this.setDimensions();
//    },
//    setDimensions : function(){
//        var height = Webadmin.Window.getHeight()-80;
//        this.content.style.height=height+"px";
//    }
//}
//
Webadmin.Page = Class.create();
Webadmin.Page.prototype = {
    initialize : function(options) {
      this.options = Object.extend({
          content : 'w-page',
          sidebar : 'w-sidebar',
          frame   : 'preview_frame'
      }, options || {});
      this.setDimensions();
      this.externalLinks();
      Event.observe(window, 'resize', this.setDimensions.bindAsEventListener(this));
    },
    setDimensions : function(){
      if ($('preview_frame')){
        $(this.options.frame).style.height = Webadmin.Window.getHeight()-168+"px";
        $(this.options.frame).style.width = Webadmin.Window.getWidth()-242+"px";
      }
      
//        if($('w-page')){
//            $(this.options.content).style.height = Webadmin.Window.getHeight()-170+"px";
//            $(this.options.content).style.width = Webadmin.Window.getWidth()-290+"px";
//            $(this.options.sidebar).style.height = Webadmin.Window.getHeight()-96+"px";
//        }
//        if($('w-iframe')){
//            $(this.options.content).style.overflow = 'hidden';
//            $(this.options.content).style.height = "auto";
//            $('w-iframe').style.height = Webadmin.Window.getHeight()-166+"px";
//            $('w-iframe').style.width = Webadmin.Window.getWidth()-250+"px";
//        }
    },
    externalLinks : function(){
        var links = document.getElementsByTagName('a');
        $A(links).each(function(link){
            if(Element.hasClassName(link, 'external')){
                Event.observe(link, 'click', this.externalWindow.bindAsEventListener(this), false);
            }
        }.bind(this));
    },
    externalWindow : function(ev){
        var element = Event.element(ev);
        Event.stop(ev);
        window.open(element.href, "Webadmin", "toolbar=no, menubar=no, width=600, height=400, resizable=yes");
    }
}
//
//
//
Webadmin.Accordion = function(){
    return {
        setup : function(){
            this.element = document.getElementById('navigation');
            Element.cleanWhitespace(this.element);
           // this.list = this.element.getElementsByTagName('li');
            this.list = $$('#navigation strong');
            this.items = Array();
            var len = this.list.length;
            var open = (Webadmin.Cookie.get("menu")!=null) ? Webadmin.Cookie.get("menu") : null;
            for(var i=0; i<len; i++){
                this.items[i] = Object();
                this.items[i].parent = this.element;
                this.items[i].index = i;
                this.items[i].header = this.list[i];
                
                //fix nex sibling find
                var n = this.list[i];
                do  n = n.nextSibling; 
                while (n && n.nodeType != 1); 
                this.items[i].body=n;
                //
               
                Event.observe(this.items[i].header, 'click', this.toggle.bind(this.items[i]));
                if(open!=null&&open==i){
                    this.items[i].open=true;
                    this.element.active = this.items[i];
                }else{
                    this.items[i].body.style.display='none';
                }
            }
        },
        toggle : function(){
            if(this.open!=true){
                if(this.parent.active){
                    new Effect.BlindUp(this.parent.active.body, {duration: 0.5});
                    this.parent.active.open = false;
                }
                new Effect.BlindDown(this.body, {duration: 0.5});
                this.parent.active = this;
                this.open = true;
                Webadmin.Cookie.set("menu", this.index, 7, '/');
            }
        }
    }
}();
//
//Webadmin.Approve = function(){
//	return {
//		setup : function(){
//      if($('approve')&&$('unarchive')){
//      	var u = $('unarchive');
//      	var a = $('approve');
//      	if(u.checked){
//      		a.disabled=false;
//      	}else{
//      		a.disabled=true;        		
//      	}
//      	Event.observe(u, 'change', this.toggle);
//      }else{
//      	return;
//      }		
//		},
//		toggle : function(e){
//			var e = Event.element(e);
//			var a = $('approve');
//			if(e.checked==true){
//				a.disabled=false;
//			}else{
//				a.disabled=true;
//				a.checked='';
//			}
//		}	
//	}
//}();

function init(){
  
  
  $$('.js_filter').each(function(element){
     
      var input=document.createElement('input')
      
      input.setAttribute('type','text')
      Element.addClassName(input,'text');
       
      input.setAttribute('name','filter[]')
             
      input.id=element.id+'_filter';
       
       
      
      var p=document.createElement('p')
      
      p.innerHTML="Type to filter this list.";
      
      element.style.marginLeft='150px';
      new Insertion.Before(element, input); 
      new Insertion.Before(element, p); 
      new Webadmin.ListFilter(input.id,element.id);
    }
  );
  
  $$('.js_ok').each(
    function(element){
      element.onclick=function(){
        var ans; 
	      ans=window.confirm('Are you sure you want to '+element.title+'?');
	      if (ans!=true) return false;
	      //add checked
	      element.href=element.href+'&check=1';
      }
    }
  );
  
  $$('input.cascade_kill').each(
    function(element){
      element.onclick=function(){
         id=element.id
         var loc=location.href.split('/');
         page=loc[loc.length-1].split('?');
         field=element.id.replace('_cascade','');
      //   query=page.spit('?')
        //var loc='coverage';
         var details = new Ajax.Request (
      		'/cms/pages/ajax/cascade.php',
      		 { 
      			method: 'post',
      			parameters: 'ajax=cascade&page='+page[0].replace('edit.php','')+'&field='+field+'&'+page[1],
      			evalScripts: true, 
					  onSuccess:function(t) { 
  						  Element.replace(id,t.responseText);			 
						}
           }
        )
      }
    }
  );
  
  $$('input.date').each(
    function(element){
      var icon= document.createElement('img');
      icon.setAttribute('src','/cms/images/icons/calendar_edit.png');
      Element.addClassName(icon,'calendar_icon');
      var target=element.id
      icon.onclick=function(){
        if (Element.hasClassName(target,'time')) 
            NewCal(target,'ddMMyyyy',true,24);
        else 
            NewCal(target,'ddMMyyyy');
      }.bind(target)
      new Insertion.After(element, icon); 
    }
  );
  
  $$('input.USAdate').each(
    function(element){
      var icon= document.createElement('img');
      icon.setAttribute('src','/cms/images/icons/calendar_edit.png');
      Element.addClassName(icon,'calendar_icon');
      var target=element.id
      icon.onclick=function(){
        if (Element.hasClassName(target,'time')) 
            NewCal(target,'MMddyyyy',true,24);
        else 
            NewCal(target,'MMddyyyy');
      }.bind(target)
      new Insertion.After(element, icon); 
    }
  );
  
  $$('.js_delete_tb_row').each(
    function(element){
      element.onclick=function(){
        var ans; 
	      ans=window.confirm('Are you sure you want to delete this item?');
	      if (ans!=true) return false;
        //find row top
        var n = element;
        do  n = n.parentNode; 
        while (n && n.tagName.toLowerCase()!='tr'); 
        
       //if no other rows find table top
       parent=n.parentNode
       if (parent.getElementsByTagName('tr').length<=2) {
          n=parent
          do  n =  n.parentNode;  
          while (n && n.tagName.toLowerCase()!='table'); 
       }               
        //remove selected element
        Element.remove(n)
        return false;
      }
      
    }
  );
  
  $$('.js_remove_img').each(
    function(element){
      element.onclick=function(){
        var ref=element.getAttribute('ref')+'_ref'
        if (!$(ref)) return true;
        var ans; 
	      ans=window.confirm('Are you sure you want to delete this image?');
	      if (ans!=true) return false;
	      
	      $(ref).value='';
        
	      //find container
        var n = element;
        do  n = n.parentNode; 
        while (n && n.tagName.toLowerCase()!='div'); 
        Element.remove(n)
        
      
        
        return false;
      }
      
    }
  );
  
  $$('#inbox th.approve, #inbox th.archive, #inbox th.unarchive').each(
    function(element){
      if (!$('table_js_extra')){
        //find table
        var newRow=document.createElement('tr')
        newRow.id='table_js_extra';
        
        var ths=element.parentNode.getElementsByTagName('th')
        ths_length=ths.length
        for (i=0;i<ths_length;i++){
          var newTd=document.createElement('td')
          newTd.id=Element.classNames(ths[i])+'_';
          newRow.appendChild(newTd);
        }
        element.parentNode.parentNode.appendChild(newRow) 
      }
      
      var target_ref=Element.classNames(element)+'_';
      var target=$(target_ref);
      var newInput =document.createElement('input');
      newInput.type='checkbox';
      newInput.id='checkbox_'+Element.classNames(element);
      newInput.onclick= function(){
        
        if (Element.classNames(element)!='approve' && $('checkbox_approve')) $('checkbox_approve').checked=false;
        if (Element.classNames(element)!='archive' && $('checkbox_archive')) $('checkbox_archive').checked=false;
        if (Element.classNames(element)!='unarchive' && $('checkbox_unarchive')) $('checkbox_unarchive').checked=false;
       // this.checked = (!this.checked)? false:true;
        
        var form=$('inbox');
        var form_length=form.elements.length
       // alert(form_length)
       // alert("input["+Element.classNames(element)+"]")
        for (var i = 0; i < form_length; i++) {
          if (Element.hasClassName(form.elements[i], Element.classNames(element))) {
           form.elements[i].checked = this.checked;
          }
        }
        return true;
       // alert('ok');
      }
      newText = document.createTextNode(' All');
      target.appendChild(newInput)
      target.appendChild(newText)
      
      
    }
    );
    
    function selectApproveRadios(form) {
      //clear other checkbox;
      document.getElementById("archiveCheckBoxId").checked = false;
      for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name.indexOf("input[approve]") > -1 && form.elements[i].value == 0) {
         form.elements[i].checked = document.getElementById("approveCheckBoxId").checked;
        }
      }
    }

  
//   $$('textarea.textarea_large, textarea.textarea_small').each(
//    function(element){
//      alert('found:'+element.id)
//      
//    }
//  );
  
 // new Webadmin.RichTextEditorForm("mainForm", {only:'editor', ul: true, ol: true});
  new Webadmin.RichTextEditorForm("wrapper", {only:'editor', ul: true, ol: true});
  Webadmin.Accordion.setup();
  
//      element.onclick=function(){
//        var ans; 
//	      ans=window.confirm('Are you sure you want to '+element.title+'?');
//	      if (ans!=true) return false;
//	      //add checked
//	      element.href=element.href+'&check=1';
//      }
    
  


  
//    var forms = document.getElementsByTagName("form");
//    $A(forms).each(function(form){
//        if(!document.all) Element.cleanWhitespace(form);
//        if(form.id!="filterForm"){
//            //new Validation(form.id, {immediate: true});
//        }
//    });
//    if($('selectCategory')){
//        Event.observe($('selectCategory'), 'change', function(e){ var url = Event.element(e).value; if(url){ window.location = url; } });
//    }
//    if(!$('w-login-wrapper')){
        var page = new Webadmin.Page();
//        Webadmin.Accordion.setup();
//				Webadmin.Approve.setup();
//    }else{
//        Webadmin.Login.initialize();
//    }
//    $$('table.sortable').each(function(element){
//        new TableSorter(element, '/AjaxService.svc');
//    });
}



Event.onReady(init);


