/**
* general.js
* Library of JS
* @copyright    Michael Reed, 2008
*/

//function $$(id){return document.getElementById(id);} 
if((typeof($$)=='undefined')&&document.getElementById)
{window.$$=function(s){return document.getElementById(s)}}

function getElementsByClassName(className)
{
    var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
    var allElements = document.getElementsByTagName("*");
    var results = [];

    var element;
    for (var i = 0; (element = allElements[i]) != null; i++)
    {
        var elementClass = element.className;
        if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
        results.push(element);
    }
    return results;
}

function getDirectKidsOfElmType(el,type)
{
    //Returns direct children of given element and for given element type.
    if(!type || !el || !el.getElementsByTagName) return;
    var k=[],a=el.getElementsByTagName(type),l=a.length,c=0,n=0;
    while(c<l) (a[c].parentNode==el)?(k[n++]=a[c++]):c++;
    return k;
}

function genThumbnail_file(location,file,dir,w)
{
  /*
        location=element to put image
        file=filename
        dir=directory relative to index
        w=desired width
  */
  var rndm = new Date();
  $$(location).src='lib/includes/thumb_file.php?file='+file+'&dir='+dir+'&w='+w+'&random='+rndm;
}

function genThumbnail_id(type,id,w)
{
  //if id=0, puts stdImage/type+thumb.bmp in location of type_thumb, else puts specific image based on type and id of width w in this location
  if (id==0) {$$(type+'_thumb').src='lib/stdimages/'+type+'_thumb.bmp';}
  else
  {
    // var rndm = new Date();
    var location = type+'_thumb';
    $$(location).src='lib/includes/thumb_id.php?type='+type+'&id='+id+'&w='+w;
  }
}

function genTemplateThumbnail_id(location,id,w)
{
  //if id=0, puts stdImage/templatethumb.bmp in location of location, else puts specific image based on id of width w in this location
  if (id==0) {$$(location).src='lib/stdimages/template_thumb.bmp';}
  else {$$(location).src='lib/includes/template_thumb_id.php?id='+id+'&w='+w;}
}

function create_xmlrequest()
{
    var xmlrequest = false;
    if (window.XMLHttpRequest) {xmlrequest = new XMLHttpRequest();}
    else if (window.ActiveXObject)
    {
        try {xmlrequest = new ActiveXObject("Msxml2.XMLHTTP");}
        catch (e1)
        {
            try {xmlrequest = new ActiveXObject("Microsoft.XMLHTTP");}
            catch (e2) { }
        }    
    }
    if (!xmlrequest) {alert ('Some functionality is unavailable for your browser.');}
    return xmlrequest;
}


function get_xml_id(file,id,location){
  /*
        file=filename
        id=primary id of table
        location=element to put image
  */
    //Why doesn't next line work?
    // if  (!isdefined('window','xmlRequest_getid')) {xmlRequest_getid=create_xmlrequest();}
    xmlRequest_getid=create_xmlrequest();
    if  (xmlRequest_getid) {
        // Create a function that will receive data sent from the server
        xmlRequest_getid.onreadystatechange = function(){
            if(xmlRequest_getid.readyState == 4&&xmlRequest_getid.status==200){
                $$(location).innerHTML = xmlRequest_getid.responseText;
                //var xmlRequest_getid=null;  //clean up variables?
                return false;
            }
        }
        xmlRequest_getid.open('GET', file+'?id='+id, true);
        xmlRequest_getid.send(null);
    }
    else {alert('Some functionality is unavailable for your browser.');}
}

function get_resource_xml_id(_r,_f,id,location)
{
  /*
        _r=resource (i.e. component or module name)
        _f=file
        id=primary id of table
        location=element to put image
  */
    xmlRequest_getresourceid=create_xmlrequest();
    if  (xmlRequest_getresourceid)
    {
        // Create a function that will receive data sent from the server
        xmlRequest_getresourceid.onreadystatechange = function()
        {
            if(xmlRequest_getresourceid.readyState == 4&&xmlRequest_getresourceid.status==200)
            {
                $$(location).innerHTML = xmlRequest_getresourceid.responseText;
                //var xmlRequest_getresourceid=null;  //clean up variables?
                return false;
            }
        }
        
        if(_r.substr(0,3)=='com'){var resource_type='components';}
        else if(_r.substr(0,3)=='mod'){var resource_type='modules';}
        else {return false;}
        
        xmlRequest_getresourceid.open('GET', 'lib/'+resource_type+'/'+_r+'/'+_f+'?id='+id, true);
        xmlRequest_getresourceid.send(null);
    }
    else {alert('Some functionality is unavailable for your browser.');}
}

function update_dynamic_table(_r,_f,id,location)
{
  /*
        _r=resource (i.e. component or module name)
        _f=file
        id=primary id of table
        location=element to put image
  */
    xmlRequest_gettable=create_xmlrequest();
    if  (xmlRequest_gettable)
    {
        // Create a function that will receive data sent from the server
        xmlRequest_gettable.onreadystatechange = function()
        {
            if(xmlRequest_gettable.readyState == 4&&xmlRequest_gettable.status==200)
            {
                var table=$$(location);
                var tbody=table.tBodies[0];
                while (tbody.rows.length> 0)
                {tbody.deleteRow(0);}

                var positions=eval("("+xmlRequest_gettable.responseText+")"); //convert json
                if(positions=='')
                {
                    //No modules in this position
                    var newRow = tbody.insertRow(-1);
                    var newCell = newRow.insertCell(0);
                    newCell.colSpan=2;
                    newCell.appendChild(document.createTextNode('No Modules in this Position'));
                } else
                {
                    //There are modules in this position
                    var k=0;
                    var arLen=positions.length;
                    for ( var i=0, len=arLen; i<len; ++i )
                    {
                        var newRow = tbody.insertRow(-1);

                        newRow.className ='row'+k;
                        newRow.id=positions[i].id;
                        var newCell0 = newRow.insertCell(0);
                        newCell0.appendChild(document.createTextNode(positions[i].module_name));
                        var newCell1 = newRow.insertCell(1);
                        newCell1.innerHTML = positions[i].moduletype_name+'<input name="moduleId[]" type="hidden" value="'+positions[i].id+'" />';
                        k=1-k;

                    }
                }

                var tableDnD = new TableDnD();
                tableDnD.init(table);
                //var xmlRequest_gettable=null;  //clean up variables?
                return false;
            }
        }

        if(_r.substr(0,3)=='com'){var resource_type='components';}
        else if(_r.substr(0,3)=='mod'){var resource_type='modules';}
        else {return false;}
        
        xmlRequest_gettable.open('GET', 'lib/'+resource_type+'/'+_r+'/'+_f+'?id='+id, true);
        xmlRequest_gettable.send(null);
    }
    else {alert('Some functionality is unavailable for your browser.');}

}

function change_template(id)
{
    xmlRequest_changetemplate=create_xmlrequest();
    if  (xmlRequest_changetemplate)
    {
        xmlRequest_changetemplate.onreadystatechange = function()
        {
            if(xmlRequest_changetemplate.readyState == 4&&xmlRequest_changetemplate.status==200)
            {
                var obj = eval("(" + xmlRequest_changetemplate.responseText + ")"); //turn json into an object
                var menu_c=$$('color_types_template_resources_id');
                menu_c.length=0;
                for(i=0; i < obj.color_types.length; i++)
                {
                    menu_c.options[i] = new Option(obj.color_types[i].name,obj.color_types[i].id);
                } 
                var menu_m=$$('menu_types_template_resources_id');
                menu_m.length=0;
                for(i=0; i < obj.menu_types.length; i++)
                {
                    menu_m.options[i] = new Option(obj.menu_types[i].name,obj.menu_types[i].id);
                } 
                var menu_s=$$('screenwidth_types_template_resources_id');
                menu_s.length=0;
                for(i=0; i < obj.screenwidth_types.length; i++)
                {
                    menu_s.options[i] = new Option(obj.screenwidth_types[i].name,obj.screenwidth_types[i].id);
                }
                //Update images for template, colors, menus
                $$('template_thumb').innerHTML = obj.template_thumb;
                $$('color_thumb').innerHTML = obj.color_thumb;
                $$('menu_thumb').innerHTML = obj.menu_thumb;
                return false;
            }
        }
        xmlRequest_changetemplate.open('GET', 'lib/components/com_admin_configuration_display/changetemplate.php?id='+id, true);
        xmlRequest_changetemplate.send(null);
    }
    else {alert('Some functionality is unavailable for your browser.');}
}

function toggleVisibility(obj,id)
{
    if(obj.value==1) {$$(id).style.display = "none";}
    else {$$(id).style.display = "block";}
}

function cloneObject(what)
{
    for (i in what)
    {
        if (typeof what[i] == 'object') {this[i] = new cloneObject(what[i]);}
        else this[i] = what[i];
    }
}


/**
//Messes up Google maps
Object.prototype.clone = function()
{
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this)
  {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {newObj[i] = this[i].clone();}
    else newObj[i] = this[i]
  } return newObj;
};
**/

// **************************************************************
function trim(str)
{
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i > 0; i--)
    {
        if (/\S/.test(str.charAt(i)))
        {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

function isdefined(object, variable)
{
    return (typeof(eval(object)[variable]) != 'undefined');
    //var temp;
    //return (myvar == temp)?0:1;
}

function getFileName(path)
{    //Returns filename given path
    //return path.replace(/^.*\\/, '')
    return /([^\\]+)$/.exec(path)[1];
    //return path.match(/[-_\w]+[.][\w]+$/i)[0];
}

function getFileNameOnly(path)
{
    //Returns filename given path without extention
    //Causes error if no path is included
    return path.match(/(.*)[\/\\]([^\/\\]+)\.\w+$/)[2];
}

function removeExtention(file)
{    //Returns filename without extentino
    return file;    //FIX!!!
}

function submitbutton(pressbutton)
{
    submitform(pressbutton);
}

function submitform(pressbutton)
{
    if (pressbutton) {document.mainForm.task.value=pressbutton;}
    if (typeof document.mainForm.onsubmit == "function")
    {document.mainForm.onsubmit();}
    document.mainForm.submit();
}

function hideMainMenu()
{
    if (document.mainForm.hidemainmenu)
    {document.mainForm.hidemainmenu.value=1;}
}

function checkAll_modified( formname, n, fldName )
{
  if (!fldName) {fldName = 'cb';}
    var f = document.mainForm;
    var c = formname.checked;
    var n2 = 0;
    for (i=0; i < n; i++)
    {
        cb = eval( 'f.' + fldName + '' + i );
        if (cb)
        {
            cb.checked = c;
            n2++;
        }
    }
}

function isChecked(isitchecked)
{
    if (isitchecked == true){document.mainForm.boxchecked.value++;}
    else {document.mainForm.boxchecked.value--;}
}

/**
* Toggles the check state of a group of boxes
*
* Checkboxes must have an id attribute in the form cb0, cb1...
* @param The number of box to 'check'
* @param An alternative field name
*/
function checkAll( n, fldName )
{
  if (!fldName) {fldName = 'cb';}
    var f = document.mainForm;
    var c = f.toggle.checked;
    var n2 = 0;
    for (i=0; i < n; i++)
    {
        cb = eval( 'f.' + fldName + '' + i );
        if (cb)
        {
            cb.checked = c;
            n2++;
        }
    }
    if (c) {document.mainForm.boxchecked.value = n2;}
    else {document.mainForm.boxchecked.value = 0;}
}

function validate_registration(thisform)
{	// Validation of required input fields
// Verify that all values are adaquate
// If error, alert error and return false.  Else no alert and return true.
var err_message = "";
with (thisform)
{
    if( first_name.value && last_name.value && email.value && user_name.value && password.value)
    {
        if( email.value==email_2.value ){ err_message=validate_email(email); }
        else {err_message="Email inputs do not match.";}
    }
    else
    {err_message="Please fill out all items.";}
}

if (err_message != "")
{
 alert(err_message);
 $$("err_msg").innerHTML = err_message+"<br>";
 return false;
}
else {return true;}
}

function validate_email(temail)
{ 
  if( temail.indexOf("@")== -1 )  // look for an @ character
   return "Invalid email - No '@'";
  else
  {
    var adr = temail.split("@");
    // look for part address before the @ character
    if(adr[0].length < 1 ) return "Invalid email - User address absent";
    else // look for a dot
    if(adr[1].indexOf(".")== -1) return "Invalid email - No dot";
    else // look for domain name after the @ character
    if(adr[1].length < 3) return "Invalid email - Incorrect Domain";
    else return "";
  }                              
}                                               

function fail(msg)	// a function to display an error message
{	alert("Email Address Error:\n" +msg);	}   


function logoff()
{
	// create new script element and set its relative URL (including ID arguments)
	var script = document.createElement( 'script' );
	script.src='lib//j/external_logoff.php?pass=okay';
	// attach (load) script element to document head
	document.getElementsByTagName( 'head' )[0].appendChild( script );
}


function check_if_logged_on()
{
if(readCookie('auth')=="yes") return true;
else {alert("Please Log In");return false;}
}

function CheckForm(form)
{
 if (form.logon_user_name.value && form.logon_password.value) return true;
 else return false;
}

function noenter()
{	//prevents enter from working
return !(window.event && window.event.keyCode == 13);
}

function enter_logon(e)
{	//calls logon() instead of enter
// alert("enter_logon-event:"+e+" event.which:"+e.which);
  if (e && (e.which == 13)){logon();}
  else{return true;}
}

function enter(nextfield)
{	//goes to next form input instead of enter (not used?)
if(window.event && (window.event.keyCode == 13))
{
    nextfield.focus();
    return false;
}
else
  return true;
}

function check_logged_on_status() {
if(readCookie('auth')=="yes") {
$$('not_logged_on').style.display = 'none';
$$('logged_on').style.display = 'block';
$$('logged_on').getElementsByTagName('h2')[0].firstChild.data = readCookie('user_name')+' is logged on';
}
// write initial cookie
cursor_wait();
var script = document.createElement( 'script' );
script.src='lib//j/external_front_door.php?pass=okay';
document.getElementsByTagName( 'head' )[0].appendChild( script );
}

function set_authorization_cookie() {
alert("set_authorization_cookie never used?");
	if(readCookie('auth')=="yes")
		$$('logoff').style.display = "block";
	else
		$$('logon').style.display = "block";
}

function generate_address( username ) {
    // writes without anchors around.
    var domain = "villascape&#46;&#99;&#111;&#109;";
    var recipient = username + "&#064;" + domain;
    var url = "&#109;&#097;&#105;&#108;&#116;&#111;:" + recipient;
    document.write(recipient.link(url));
}


function table_cell_to_string(table_id,column_no)
{
    // alert(table_id.id+".rows.length="+table_id.rows.length);
    if(table_id.rows.length>0)
    {
    var a_php = "";
    var glue="";
    for (var i=0; i<table_id.rows.length; i++)
    {
        // alert(table_id.id+".rows["+i+"].cells["+column_no+"].firstChild.data="+table_id.rows[i].cells[column_no].firstChild.data);
        a_php += glue+table_id.rows[i].cells[column_no].firstChild.data;
        glue="~";
	}
    return a_php;
    } else {return null;}
}

function table_value_to_string(table_id,column_no)
{
    if(table_id.rows.length>0)
    {
        var a_php = "";
        var glue="";
        for (var i=0; i<table_id.rows.length; i++)
        {
            a_php += glue+table_id.rows[i].cells[column_no].firstChild.value;
            glue="~";
        }
    return a_php;
    }
    else {return null;}
}

function table_input_to_string(table_id,column_no)
{
    if(table_id.rows.length>0)
    {
        var a_php = "";
        var glue="";
        for (var i=0; i<table_id.rows.length; i++)
        {
	        a_php += glue+table_id.rows[i].cells[column_no].firstChild.value;
            glue="~";
        }
        return a_php;
    }
    else {return null;}
}


function styleMenu(currMenu)
{
 	var thisMenu = $$(currMenu).style
	if (thisMenu.display == "block") {thisMenu.display = "none";}
	else {	thisMenu.display = "block";}
}

function validate(f)
{ 
    var re = /^[0-9,.]*$/; 	//Why are comma's allowed?
    window.status = "";
    if (!re.test(f.value))
    { 
        window.status = "Invalid input.";
        f.value = f.value.replace(/[^0-9,.]/g,""); 
    } 
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = unescape(document.cookie).split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}

function get_radio_value(myrad)
{
    var i=0, r, radValue;
    while(r=myrad[i++]){r.checked?radValue=r.value:null;}
    return radValue;
}

// isIntegerInRange (STRING s, INTEGER a, INTEGER b)
   function isIntegerInRange (s, a, b)
   {
       if (isEmpty(s))
         if (isIntegerInRange.arguments.length == 1) return false;
         else return (isIntegerInRange.arguments[1] == true);

      // Catch non-integer strings to avoid creating a NaN below,
      // which isn't available on JavaScript 1.0 for Windows.
      if (!isInteger(s, false)) return false;

      // Now, explicitly change the type to integer via parseInt
      // so that the comparison code below will work both on
      // JavaScript 1.2 (which typechecks in equality comparisons)
      // and JavaScript 1.1 and before (which doesn't).
      var num = parseInt (s);
      return ((num >= a) && (num <= b));
   }

   function isInteger2 (s)
   {
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
   }

function isEmpty(s)
{
    return ((s == null) || (s.length == 0))
}

function isDigit (c)
{
    return ((c >= "0") && (c <= "9"))
}

function isNumeric(num)
{
    if (num == parseFloat(num))
    return true;
    return false;
}

function isNumeric2(num)
{
    if (num >=0 || num < 0 || num==0)
    return true;
    return false;
}

function isInteger(num)
{
    if (num == parseInt(num))
    return true;
    return false;
}

function IsPhonenumber(myNumber)
{
    myRegExp = '/(\d\d\d) \d\d\d-\d\d\d\d/';
    if(myRegExp.test(myNumber))
    {return false;}
    else {return false;}
}

function disable_links()
//Disables all links
{
    var theLinks = document.getElementsByTagName("a");
    for(var i = 0; i < theLinks.length; i++)
    {
        theLinks[i].onclick = function()
        {return false;}
    }
}

function newwindow(url)
{
  var d = document;
  var _docW = (d.width != undefined) ? d.width : d.body.offsetWidth;
  var _docH = Math.max(d.documentElement.clientHeight, d.documentElement.scrollHeight);
  if(window.innerHeight > _docH) {_docH = window.innerHeight;}
  _docH = Math.max(_docH,d.body.scrollHeight);
  if(d.documentElement.clientHeight > 0) {_docW = d.documentElement.scrollWidth;}
  else{_docW = d.body.scrollWidth;}
  var _docS = (d.all ? Math.max(d.body.scrollTop,d.documentElement.scrollTop) : window.pageYOffset);
  var _docPH = (d.all ? Math.max(d.body.clientHeight,d.documentElement.clientHeight) : window.innerHeight);
  if(d.all)
  {if(d.documentElement.clientHeight > 0){_docPH = d.documentElement.clientHeight;}}
  if(window.opera) {_docPH = window.innerHeight;}
  if(!$$('popup_bg'))
  {
    var popup_bg = d.createElement('div');
    popup_bg.style.display = 'none';
    popup_bg.id = 'popup_bg';
    d.getElementsByTagName('body').item(0).appendChild(popup_bg);
  } else {var popup_bg = $$('popup_bg');}
    
  with (popup_bg.style)
  {
    position = 'absolute';
    backgroundColor = '#000';
    left = '0px';
    top = '0px';
    zindex = 10001;
    filter = 'alpha(opacity=60)';
    opacity = .60;
    width = _docW +'px';
    height = _docH +'px';
    display = 'block';
  }

  if(!$$('popup_c'))
  {
    var popup_c = d.createElement('div');
    popup_c.style.display = 'none';
    popup_c.id = 'popup_c';
    d.getElementsByTagName('body').item(0).appendChild(popup_c);
  }
  else {var popup_c = $$('popup_c');}

  with (popup_c.style)
  {
    width = '800px';
    height = '540px';
    position = 'absolute';
    top = (((_docPH-500)/2) + _docS) + 'px';
    left =  (((_docW - 800)/2) > 0 ? (((_docW - 800)/2) - 50) + 'px' : '10px');
    backgroundColor = '#000';
    zindex = 10003;
    display = 'block';
  }
  popup_c.innerHTML = '<div style="margin:8px 0px 0px 10px;float:left;font-family:verdana;color:#fff;font-size:10px;"><a href="http://www.villascape.com" target="_blank" style="color:#FFF;font-weight:bold;text-decoration:none;">Villascape.com</a></div><a href="javascript:popup_close();"><img src="lib/stdimages/close.gif" border="0" title="Close"  style="float:right;margin:5px 10px 0px 0px;" /></a>';

  if(!$$('popup_i'))
  {
    var popup_i = d.createElement('iframe');
    popup_i.id = 'popup_i';
    d.getElementsByTagName('body').item(0).appendChild(popup_i);
  }
  else{var popup_i = $$('popup_i');}

  if(document.all)
  //Changed below line
  {popup_i.scrolling = 'yes';}
  if(isInteger(url))
  {
    //popup_i.src='lib/includes/getcomponent.html';
    //popup_i.src='lib/includes/getcomponent.php?id='+url;
    popup_i.src = 'index.php?iframe=1&pid='+url;
  }
  else {popup_i.src = url;}

  with (popup_i.style)
  {
    position = 'absolute';
    height = '500px';
    display = 'none';
    margin = '0px';
    padding = '0px';
    width = '780px';
    border = '0px';
    backgroundColor='#88ffee';
    top = (((_docPH-480)/2) + _docS + 20) + 'px';
    left =  (((_docW - 780)/2) > 0 ? (((_docW - 780)/2) - 50) + 'px' : '10px');
    zindex = 10005;
    display = 'block';
  }
}

function popup_close()
{
  $$('popup_bg').style.display = 'none';
  $$('popup_i').style.display = 'none';
  $$('popup_c').style.display = 'none';
}

function admin_general()
{
    //alert("admin_general");
    $$('component_general').style.display = "block";
    $$('component_specific').style.display = "none";
    $$('horizontal_tabs_general').className  = "selected";
    $$('horizontal_tabs_specific').className  = "";
}
function admin_specific()
{
    //alert("admin_specific");
    $$('component_general').style.display = "none";
    $$('component_specific').style.display = "block";
    $$('horizontal_tabs_specific').className  = "selected";
    $$('horizontal_tabs_general').className  = "";
}

