var Window = Class.create();
Window.prototype =
{
	initialize: function()
	{
		var myWidth = 0, myHeight = 0;
		if (typeof(window.innerWidth) == 'number')
		{
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		}
		else if (document.documentElement &&
				(document.documentElement.clientWidth || document.documentElement.clientHeight))
		{
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		}
		else if (document.body && (document.body.clientWidth || document.body.clientHeight))
		{
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		this.width = myWidth;
		this.height = myHeight;
	},
	getWidth: function()
	{
		return this.width;
	},
	getHeight: function()
	{
		return this.height;
	}
}

var Popup = Class.create();
Popup.prototype = 
{
  initialize: function(options)
  {
    this.options = {
      url: "#",
      width: 300,
      height: 300,
      left: 0,
      top: 0
    }
    Object.extend(this.options, options || {});
    window.open(this.options.url, "", "width="+this.options.width+",height="+this.options.height+",left="+this.options.left+",top="+this.options.top);
  }
}

function logInSubmit()
{
    $('current_url_id').value = document.location;
    $('login_form').submit();
}

/*
Adds a new slot as a result of the New button
*/
function addNewSlot(id, func,page,slot_name,site)
{
    var nrSlots = $(id).childElements().length+1;
    nrSlots = checkDuplicate(nrSlots,slot_name);
    new Ajax.Updater(id, func, {
        asynchronous:false, 
        evalScripts:true,
        insertion:'bottom', 
        parameters:'slots_nr='+nrSlots+'&page='+page+'&name='+slot_name+'&site_name='+site});
}

/*
Checks if an element with that id doesn't already exist.
If it already exists, increment nrSlots and verify it
*/
function checkDuplicate(nrSlots,slot_name)
{
    if($('slot_'+slot_name+nrSlots))
    return checkDuplicate(nrSlots+1,slot_name);
    
    else return nrSlots;
}

function getTreePages(site,nr,id,func)
{
    if(id == '') $('create_position'+nr).innerHTML='<option value="">Select a tree</option>';
    else
    new Ajax.Updater('create_position'+nr, func, {
        asynchronous:false, 
        evalScripts:false,
        parameters:'tree='+id+'&site='+site});
}

function getSiteTrees(site,nr,func,func2)
{
    if(!site > 0) 
    {
      $('create_position4').innerHTML = '<option value="">Select a site</option>';
      $('site_homepage').innerHTML = '';
    }
    else 
    {
    new Ajax.Updater('create_position'+nr, func, {
        asynchronous:false, 
        evalScripts:false,
        parameters:'?site='+site});
    new Ajax.Updater('site_homepage', func2, {
        asynchronous:false, 
        evalScripts:false,
        parameters:'?site='+site});
    }    
}

/*
Function that checks type of a switch.
If switch is core type, try to get selected blade and retrieve available ports for that blade
Otherwise, hide blades and show all available ports for the switch 
*/
function checkType(s)
{   
    if(s>0) //make sure the function is called when a valid switch is selected
    {
        new Ajax.Updater('servers_switch_switch_has_blade', '/equipment/filterSwitchBlades', {asynchronous:false, evalScripts:false, parameters:'value='+s});
        var blade = $('servers_switch_switch_has_blade').options[$('servers_switch_switch_has_blade').selectedIndex].value;
        if(blade < 0) 
        {
            $($('servers_switch_switch_has_blade').parentNode.parentNode).hide();
            new Ajax.Updater('servers_switch_switch_has_port_id', '/equipment/filterSwitchPorts', {asynchronous:true, evalScripts:false, parameters:'value='+s});
        }
        else 
        {
            $($('servers_switch_switch_has_blade').parentNode.parentNode).show();
            new Ajax.Updater('servers_switch_switch_has_port_id', '/equipment/filterSwitchPorts', {asynchronous:true, evalScripts:false, parameters:'value='+blade+'&value2='+s});

        }
    }
}

function checkedAll(checked)
{
    if(checked == false ) $('sf_admin_list_batch_checkbox').checked = false;
    checkButtons = document.getElementsByTagName('input');
    allchecked = true;
    for(i=0;i<checkButtons.length;i++)
    if(checkButtons[i].type == 'checkbox' && checkButtons[i].name=='ids[]' && checkButtons[i].checked == false) allchecked=false;
    
    if(allchecked == true) $('sf_admin_list_batch_checkbox').checked=true;
}


// Function that gets available ports for a given blade
function getBladePorts(blade)
{
    var switch_id = $('servers_switch_switch_id').value;
    // call function only if a valid switch is selected
    if(switch_id > 0)
    new Ajax.Updater('servers_switch_switch_has_port_id', '/equipment/filterSwitchPorts', {asynchronous:true, evalScripts:false, parameters:'value2='+blade+'&value='+switch_id});
}


var toggle= false;
function toggle_func()
{
    if(!toggle)
    {
        Element.show('filters');
        toggle = true;
        document.getElementById("toggle_filters").innerHTML = 'Hide filters';
    }
    else
    {
        Element.hide('filters');
        toggle = false;
        document.getElementById("toggle_filters").innerHTML = 'Show filters'; 
    }
}

/*
Function that retrieves customized messages for the approval of colocation logs
*/
function checkApprovalForm(val, id)
{
  if(val == '') $('status').hide();
  else
  {
  	  // interogate server for the values that should be changed and populate some local values
     new Ajax.Updater('response', 
     				'/backend.php/colocation_log/statusChoice', 
     				{
     					asynchronous:false, evalScripts:false, parameters:'status='+$('approve').value+'&id='+id,
     					onCreate: function(transport) { Element.show('spinner'); },
     					onSuccess: function(transport) { Element.hide('spinner'); }  					
     				});
     $('submit_id').value = $('button_response').value;
     $('subject').value = $('subject_response').value;

     var ed = tinyMCE.get('content');
     ed.setContent($('content_response').innerHTML);
     
     $('status').show();
  }  
}


//function to change menus - postponed
function changeMenu(anc,divid)
{
/*  
alert(anc.parentNode.parentNode.parentNode.childNodes[0]);
$(divid).toggle('slow');


$$('div.upper_button').each(Element.toggleClassName(this,'grey'));
$$('div.lower_button').each(Element.toggleClassName(this,'grey'));
*/
}

//function to change available rack types based on rack id
function changeRackTypes(rack)
{
   if(rack > 0) 
   new Ajax.Updater('rack_parts_rack_part_type_id', '/rack_parts/getRackTypes', {asynchronous:true, evalScripts:false, parameters:'rack_id='+rack}); 
}

function getRackPartsLocation()
{
    var location = $('servers_location_position_location_id').options[$('servers_location_position_location_id').selectedIndex].value;
    var foot_x = $('servers_location_position_footprint_x_id').options[$('servers_location_position_footprint_x_id').selectedIndex].value;
    var foot_y = $('servers_location_position_footprint_y_id').options[$('servers_location_position_footprint_y_id').selectedIndex].value;
    
    if(location >0 && foot_x > 0 && foot_y > 0)
    new Ajax.Updater('servers_rack_part', '/rack_parts/getRackOnLocation', {asynchronous:true, evalScripts:false, parameters:'location='+location+'&footx='+foot_x+'&footy='+foot_y});  
    else alert('Please select a valid Location and footprints');    
}


/* Check if user inserted external link*/
function checkExternal(slot_name)
{
    var ok = false;
    if($('check_'+slot_name)!=null)
    {
        new Ajax.Updater('validate_external_check_'+slot_name, '/sfSimpleCMS/checkExternal', {
            asynchronous:false, 
            evalScripts:false,
            onComplete: function(transport)
            {
                if(transport.responseText=='') 
                {
                    if($('check_'+slot_name).checked)
                    {
                        var position_http = $('url_'+slot_name).value.indexOf('http://');
                        var position_https = $('url_'+slot_name).value.indexOf('https://');
                        if(position_http<0 && position_https<0)
                            $('url_'+slot_name).value='http://'+$('url_'+slot_name).value;
                    }
                }
                else
                {
                    ok = true;
                } 
                 
            },
            parameters:'checked='+$('check_'+slot_name).checked+'&url='+$('url_'+slot_name).value+'&site_id='+$('site_id_'+slot_name).value});
    }
    if(!ok)
    {
        submitForm('edit_'+slot_name);
    }      
}

function submitForm(formId)
{
 if($(formId).onsubmit())
 {
    $(formId).submit();
 }
}

//displays subemnu for quick menu items on mouseover
function showQuickSubmenu(anc, id)
{
if($('quick_menu')) 
{
    links=$('quick_menu').getElementsByTagName('a');
    for(i=0;i<links.length;i++)
    {
        links[i].style.fontWeight='100';
        links[i].style.color='#000000';
    }
}
anc.style.color='#EE3531';
anc.style.fontWeight='700';
if($('quick_submenu_'+id)) $('quick_submenu').innerHTML = $('quick_submenu_'+id).innerHTML;
}


//Get X position
function getElementX(elem)
{
    var x=0;
    while(elem)
    {
        x += elem.offsetLeft;
        elem=elem.offsetParent;
    }
    return x;
}

//Get Y position
function getElementY(elem)
{
    var y=0;
    while(elem)
    {
        y += elem.offsetTop;
        elem=elem.offsetParent;
    }
    return y;
}

function $style(elem, CssProperty)
{
    function $(stringId)
    {
        return document.getElementById(stringId);
     }   

    if(elem.currentStyle)
   {
        var convertToCamelCase = CssProperty.replace(/\-(.)/g, function(m, l){return l.toUpperCase()});
        return elem.currentStyle[convertToCamelCase];
    }
    else if (window.getComputedStyle)
   {
        var elementStyle = window.getComputedStyle(elem, "");
        return elementStyle.getPropertyValue(CssProperty);
    }
}

function GetWidth()
{
        var x = 0;
        if (self.innerHeight)
        {
          x = self.innerWidth;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
        {
                x = document.documentElement.clientWidth;
        }
        else if (document.body)
        {
                x = document.body.clientWidth;
        }
        return x;
}

function GetHeight()
{
        var y = 0;
        if (self.innerHeight)
        {
                y = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)
        {
                y = document.documentElement.clientHeight;
        }
        else if (document.body)
        {
                y = document.body.clientHeight;
        }
        return y;
}

function addNews(edit, preview, site_name)
{
      $('wall').style.display = 'block';
      $('add_news_visible').style.display = 'block';
      $('wall').style.width = document.body.clientWidth+'px';
      $('wall').style.height = document.body.clientHeight+'px';
      $('wall').style.opacity = "0.7";
//    $('wall').className = 'transparent_class';

   
    new Ajax.Updater('add_news_visible', '/home/addNewsItem', {
            asynchronous:false, 
            evalScripts:true,
            onComplete: function(transport)
            {
                
            },
            parameters: 'edit='+edit+'&preview='+preview+'&site_name='+site_name
            });
    
    if($('add_news_visible') && $('add_news_visible').innerHTML=='') document.location.reload();
}

function hideForm()
{
    $('wall').style.display = 'none';
    $('add_news_visible').style.display = 'none';

}
function verifyNews(edit, preview, site_name, action)
{
    $('news_overview_content').innerHTML = tinyMCE.activeEditor.getContent({format : 'raw'});
    new Ajax.Updater('add_news_visible', action, {
            asynchronous:false, 
            evalScripts:true,
            onComplete: function(transport)
            {
                if(transport.responseText!='NOK')
                {
                    addNews(edit, preview, site_name);
                }
                else
                {
                    document.location.href = transport.responseText;
                    $('wall').style.display = 'none';
                    $('add_news_visible').style.display = 'none';
                }
            },
            parameters: 'edit='+edit+
                        '&preview='+preview+
                        '&site_name='+site_name+
                        '&slug='+$('news_overview_slug').value+
                        '&news_title='+$('news_overview_news_title').value+
                        '&image_name='+$('news_overview_image_name').value+
                        '&heading='+$('news_overview_heading').value+
                        //'&content='+document.getElementsByName('news_overview[content]')[0].value
                        '&content='+$('news_overview_content').value
            });
}

function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }

		 if (str.indexOf(" ")!=-1){
		    return false
		 }
 		 return true
	}

function validateUsername(fld) {
    
    var illegalChars = /[^A-Za-z\' ]/;  // allow letters

    if (fld.value == "") {
        return false
    } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
        return false
    } else if (illegalChars.test(fld.value)) {
        return false
    } else        
    return true;
}

// validates the contact form
function ValidateForm(){
	var emailID=$('contact').txtEmail
    error=false

    if ((emailID.value==null)||(emailID.value=="")||(echeck(emailID.value)==false)){
		$('email-error').style.display='block'
        Modalbox.resizeToContent();
		emailID.focus()
                error=true
	}
    else
    $('email-error').hide();
        
    if (!validateUsername($('contact').name)) {
        $('name-error').style.display='block'
        Modalbox.resizeToContent();
        error=true
    }
    else {
        $('name-error').hide();
    }

    if ($('contact').message.value.length < 5) {
        $('message-error').style.display='block'
        Modalbox.resizeToContent();
        error=true
    }
    else {
        $('message-error').hide();
    }

    Modalbox.resizeToContent();

    if (error){
        return false
    }
    else {
        return true
    }
 }

// validates the bel me terug form
function ValidateBMTForm(){
    error=false;

    if (!validateUsername($('bel-me-terug').name)) {
        $('bel-me-terug-name-error').style.display='block'
        Modalbox.resizeToContent();
        error=true
    }
    else {
        $('bel-me-terug-name-error').hide();
    }

    if ($('bel-me-terug').subject.value.length < 5) {
        $('bel-me-terug-subject-error').style.display='block'
        Modalbox.resizeToContent();
        error=true
    }
    else {
        $('bel-me-terug-subject-error').hide();
    }

    Modalbox.resizeToContent();

    if (error){
        return false
    }
    else {
        return true
    }
 }

// validates subscription form
function ValidateSubscriptionForm(){
    error=false;
    var emailID=$('subscription').txtEmail

    if ((emailID.value==null)||(emailID.value=="")||(echeck(emailID.value)==false)){
		$('subscribe-email-error').style.display='block'
        Modalbox.resizeToContent();
		emailID.focus()
                error=true
	}
    else
    $('subscribe-email-error').hide();

    Modalbox.resizeToContent();

    if (error){
        return false
    }
    else {
        return true
    }
 }

function move_slots(node,positionX){
        element__=node.getOffsetParent();
//        alert(node.identify()+' has left: '+node.style.left);
//        alert('parrent offset is :' + element__.cumulativeOffset());
        var x=positionX-element__.cumulativeOffset()[0];
//        alert('desired offset is: '+x);
        node.style.left=x+'px';
//        alert('new node offset is: '+node.style.left);

    }
//    function dragg_stuff () {
//        var editables__=$$('form.edit_slot');
//        var max__=editables__.length;
//        var i=0;
//        for (i=0;i<=(max__-1);i++)
//        {
//            editables__[i].insert({top: '<div class="caption">Edit Content'+'</div>'});
//            new Draggable(editables__[i].parentNode.identify());
//            if (editables__[i].parentNode.cumulativeOffset()[0] > body__.getWidth()){
//                var positionX=body__.getWidth()- editables__[i].parentNode.getWidth();
////                alert(body__.getWidth()- editables__[i].parentNode.getWidth()+'px');
////                alert('got it on '+editables__[i].parentNode.identify());
//                move_slots(editables__[i].parentNode,positionX);
//            }
//            Event.observe(editables__[i].parentNode.previousSiblings()[0].identify(), 'dblclick', function(event) {
//              alert(Event.element(event).identify());
//            });
//        }
//    }
//    var body__=$$('body')[0];
//
////    Event.observe(body__, 'load', dragg_stuff());
//  Event.observe(window, 'load', function() {
//  dragg_stuff ();
//  alert('');
//});

function validateNews(site, link)
{
    var tiny_value = tinyMCE.activeEditor.getContent({format : 'raw'});
    
    //hide the required error messages
    if($('news_overview_news_title_error')) $('news_overview_news_title_error').hide();
    if($('news_overview_slug_error')) $('news_overview_slug_error').hide();
    if($('news_overview_image_name_error')) $('news_overview_image_name_error').hide();
    
    $('news_overview_news_title').style.border = '1px solid #7F9DB9'; 
    $('news_overview_slug').style.border = '1px solid #7F9DB9'; 
    $('news_overview_image_name').style.border = '1px solid #7F9DB9'; 
    
    if($('news_overview_news_title').value == '')
    {
        showError('news_overview_news_title','Required field!');               
        return false;
    }
    if($('news_overview_slug').value == '')
    {
        showError('news_overview_slug','Required field!');  
        return false;
    }

    // escape in case of "?" - for query strings
    var news_title = escape($('news_overview_news_title').value);
    
    new Ajax.Request(link,{
      method: 'post',
      asynchronous:false, 
      evalScripts:true,
      onComplete: function(transport)
      {
          if(transport.responseText!=$('news_overview_slug').value)
          {
              var id = 'news_overview_'+transport.responseText.substring(0,transport.responseText.indexOf(' '));
              if($(id))
              {
                  showError(id,transport.responseText.substring(transport.responseText.indexOf(' ')+1));
              }
          }
          else
          {
              document.location.href = 'http://'+document.location.host+'/'+$('news_overview_slug').value;
          }
      },
      parameters: 'site_name='+site+
            '&slug='+$('news_overview_slug').value+
            '&news_title='+news_title+
            '&image_name='+$('news_overview_image_name').value+
            '&heading='+$('news_overview_heading').value+
            '&content='+tiny_value
      
    }
    )
  
}

function showError(id,message)
{
    $(id).style.border = '1px solid red';
    if($(id+'_error'))
    {
        $(id+'_error').innerHTML = message;
        $(id+'_error').show();  
    }
    else
    {
    var error_div = document.createElement('div');
    error_div.setAttribute('id',id+'_error');
    error_div.setAttribute('style','color:red');
    error_div.setAttribute('class','errorValid');
    error_div.innerHTML = message;
    var br = document.createElement('br');
    $(id).parentNode.appendChild(br);
    $(id).parentNode.appendChild(error_div);
    }
}