checkBrowserWidth();

attachEventListener(window, "resize", checkBrowserWidth, false);

var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread

/*
 *  getXMLHttpObj - obtains an XmlHTTP request object or it's equivalent
 *                  ActiveX object for IE 8 and below
 */
if(typeof(XMLHttpRequest)!='undefined'){    
    var getXMLHttpObj = function(){ return new XMLHttpRequest(); }} 
else { 
    var getXMLHttpObj = function() {        
    
        var activeXObjects = ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0', 
                              'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 
                              'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
        for ( var i = 0; i < activeXObjects.length; i++ ){            
            try {                
                return new ActiveXObject(activeXObjects[i]);            
            } catch( err ){}        
        }
    }
}

var oXml = getXMLHttpObj();             // HTTP XML Request Object
var elemAjax = null;                    // HTML elem where AJAX response placed
var inputting = false;                  // whether currently inputting


/*
 *  ocPopup - calls a popup window 
 *
 *   IN: url - URL to display in the window
 */
function ocPopup( url ) {
    window.open( url, 'ocPopup',
		'scrollbars=0,statusbar=1,resizable=1,width=600,height=510');
}


/*
 *  show - makes all controls within specified element visible 
 *
 *   IN: elem - element inside which all controls made visible
 */
function show( elem, reqdClass ) {  
    var reqdClass = reqdClass || 'control';
    var controls = getElementsByClassName( reqdClass, null, elem );  
    for ( var i = 0; i < controls.length; i++ )
        controls[i].className = removeClass( controls[i].className, 'hidden' );
    return true;
}


/*
 *  hide - hides all controls within specified element
 *
 *   IN: elem - element inside which all controls are hidden
 */
function hide( event, elem, reqdClass ) {  

    if ( !event ) var event = window.event;

    var src = event.srcElement || event.target;
    if ( src.nodeName === 'INPUT' ) return;
    
    var reqdClass = reqdClass || 'control';
    var controls = getElementsByClassName( reqdClass, null, elem );    
    for ( var i = 0; i < controls.length; i++ )
        controls[i].className += " hidden";
    return true;
}


/* small diagnostic function to write out node details */
/*
function toString( node ) {
    var desc = '<' + node.nodeName;
    if ( node.id ) desc += ' id="' + node.id + '"';
    if ( node.className ) desc += ' class="' + node.className + '"';
    return desc + '>';
}
*/


/**
 *  Determines what event happened at specified element 
 *
 *  @param  elem    HTMLNode node at which event being checked
 *  @param  event   object event object
 *  @return string|null event type that happened at node, or null if event
 *                      didn't happen specified element
 */
function eventAtElement( elem, evt ) {
    
    /* Event object passed in as an argument or must be obtained from window
       object in case of (older?) IE browsers */
       
    if ( !evt ) var evt = window.event;
    
    /* occurredAt is element where this event is occurring - return
       null if this is not elem */
       
    var occurredAt = evt.srcElement || evt.target;
    // alert( toString( occurredAt ) );
    if ( occurredAt != elem ) return null;

    /* If this is a mouseover or mouseout event then need to check
       which element moving from/to respectively. For all other event types
       can now just return the event type */
       
    var neighbour;
    if ( evt.type == 'mouseover' )
        neighbour = evt.fromElement || evt.relatedTarget;
    else if ( evt.type == 'mouseout' )
        neighbour = evt.toElement || evt.relatedTarget;
    else
        return evt.type;

    /* Specific hack for non-IE browsers so mouseout is not triggered
       when moving from control area into rest of boundary area */
       
    if ( evt.relatedTarget && neighbour !== undefined &&
         evt.type === 'mouseout' && 
         neighbour.className.indexOf( 'boundary' ) !== -1 )
        return null;
        
    /* for mouseover/out events need to rule out movement across boundary
       with a child node */

    // alert( evt.type + ' at ' + toString( occurredAt ) + 
    //       ', neigh = ' + toString( neighbour ) );
    
    return neighbour !== undefined &&
           neighbour.parentNode == occurredAt ? null : evt.type;
}    


/**
 *  Makes elements with specified class visible in widget
 *
 *  @param  declaredAt HTMLNode node where event handler declared
 *  @param  evt        object browser event
 *  @param  reqdClass  string class(es) to make visible
 */
function show1( declaredAt, evt, reqdClass ) {
    if ( eventAtElement( declaredAt, evt ) ) {
        var reqdClass = reqdClass || 'control';
        var widget = getParentByClass( declaredAt, 'widget1' );
        var controls = getElementsByClassName( reqdClass, null, widget );  
        for ( var i = 0; i < controls.length; i++ )
            controls[i].className = 
                            removeClass( controls[i].className, 'hidden' );
    }
}


/**
 *  Hides control within a widget - only does this if the input area of
 *  widget is not showing.
 *  
 *  @param  where   HTMLNode where event handler is declared
 *  @param  evt     object browser event
 */
function hideControl( where, evt ) {
    if ( eventAtElement( where, evt ) ) {
        var widget = getParentByClass( where, 'widget1' );
        
        var input = getElementsByClassName( 'input', null, widget );
        if ( input[0].className.indexOf( 'hidden' ) !== -1 ) {
            var controls = getElementsByClassName( 'control', null, widget );  
            for ( var i = 0; i < controls.length; i++ )
                controls[i].className += " hidden";
        }
    }
}


/**
 *  Hides input area within a widget.
 *  
 *  @param  where   HTMLNode where event handler is declared
 *  @param  evt     object browser event
 */
function hideInput( where, evt ) {
    if ( eventAtElement( where, evt ) ) {
        var widget = getParentByClass( where, 'widget1' );        
        var input = getElementsByClassName( 'input', null, widget );
        input[0].className += ' hidden';
    }
}



function show2( where, reqdClass ) {

    var reqdClass = reqdClass || 'control';

    /* Identify widget we are in */
    
    var widget = getParentByClass( where, 'widget1' );

    /* if showing a control check we are not inputting elsewhere - if we are
       then leave without showing control, otherwise set the widget style
       to editable to show area that can be changed */
       
    if ( reqdClass.indexOf( 'control' ) !== -1 ) {
        if ( inputting ) return;
        widget.className += ' editable';
    } else if ( reqdClass.indexOf( 'input' ) !== -1 ) {
        inputting = true;
    } else if ( reqdClass.indexOf( 'remove' ) !== -1 ) {
    	inputting = true;
    }

    /* find widget children of required class, removing hidden class
       to make them appear */
       
    var show = getElementsByClassName( reqdClass, null, widget );  
    for ( var i = 0; i < show.length; i++ )
        show[i].className = removeClass( show[i].className, 'hidden' );
    }

    
function hide2( where, reqdClass ) {
	
	
    var reqdClass = reqdClass || 'control';

    /* Identify widget we are in. and its input element */
    
    var widget = getParentByClass( where, 'widget1' );
    var input = getElementsByClassName( 'input', null, widget );

    /* Hide elements unless we are trying to hide a widget control and
       the inut area is visible */
       
    if ( reqdClass.indexOf( 'input' ) !== -1 || reqdClass.indexOf( 'remove' ) !== -1 ||
         input[0].className.indexOf( 'hidden' ) !== -1 ) {

        /* if hiding control then remove widget's editable style */
        
        if ( reqdClass.indexOf( 'control' ) !== -1 )
            widget.className = removeClass( widget.className, 'editable' );
        
        /* if hiding input then set inputting global to false, so that
           another area can be edited */
           
        if ( reqdClass.indexOf( 'input' ) !== -1 ) inputting = false;
            
        if ( reqdClass.indexOf( '' ) !== -1 ) inputting = false;
        
        

        /* now actually hide specified elements by adding "hidden" style */
        
        var hide = getElementsByClassName( reqdClass, null, widget );  
        for ( var i = 0; i < hide.length; i++ ) hide[i].className += ' hidden';
    }
}


function uploadImage() {
    var elem = document.getElementById( 'group-logo' );
    show( elem, 'uploading' );
    document.uploadimage.submit();
    return true;
}


function updateImage( where ) {
    var widget = getParentByClass( where, 'widget1' );
    var input = getElementsByClassName( 'input', null, widget );
    input[0].className += ' hidden';
    var control = getElementsByClassName( 'control', null, widget );
    control[0].className += ' hidden';
    var updating = getElementsByClassName( 'updating-img', null, widget );
    updating[0].className = removeClass( updating[0].className, 'hidden' );
    document.uploadimage.submit();
    return true;
}

/*
 *  editWidget - submits the request to "edit" the contents of a widget
 *               via an AJAX request.
 */
function editWidget( where, event ) {
    
    /* Locate the parent widget1 tag, and remove the editable class
       so that it no longer has the "editable" style */
    
    var widget = getParentByClass( where, 'widget1' );
    widget.className = removeClass( widget.className, 'editable' );
    
    /* Locate any "updating" element in widget and make it visible -
       this causes the updating icon to appear */
       
    var updating = getElementsByClassName( 'updating', null, widget );
    if ( updating != '')
        updating[0].className = removeClass( updating[0].className, 'hidden' );
    
    /* Submit the form within the widget, specifying the JSON handler
       to deal with the JSON response */
       
    ocAjaxForm( where, owJSONHandler );
    
    return false;
    
}

function updateWidget( where ) {
 
 	
    var widget = getParentByClass( where, 'widget1' );
    widget.className = removeClass( widget.className, 'editable' );
    var updating = getElementsByClassName( 'updating', null, widget );
    updating[0].className = removeClass( updating[0].className, 'hidden' );
    elemAjax = widget;
    ocAjaxForm( where );
    
    return false;
    
}

/*
 *  pageWidget - deprecated function to page widget results - planned for
 *               removal when all code moved to class-based Widgets. Superseded
 *               by "pageResults". 
 */
function pageWidget( where, url ) {

    elemAjax = getParentByClass( where, 'widget1' );

    oXml.open( 'GET', url, true );
    oXml.onreadystatechange = ocInsertAjaxResponse;
    oXml.send('');    
    
    return false;
}

/*
 *  pageResults - handles user clicking on control to page a widget's results.
 */
function pageResults( where, url ) {
    
    oXml.open( 'GET', url, true );
    oXml.onreadystatechange = owJSONHandler;
    oXml.send('');    
    
    return false;
}


/*
 *  owJSONHandler - handles JSON response from an AJAX request. This function
 *                  can place multiple HTML fragments in different places on
 *                  the web page, as well as executing some Javascript. This
 *                  function is registered as the handler when AJAX request
 *                  is made.
 */ 
function owJSONHandler() {

    /* Do nothing if this is not the substantive response */
    
    if ( oXml.readyState != 4 ) return;  
        
    /* Turn the JSON response into a Javascript object (uncomment eval
       statement to see Ajax response as a browser alert ) */
    
    // eval( alert( oXml.responseText ) );
    var response = eval( '(' + oXml.responseText + ')' );
    
    /* Loop over any HTML fragments included in the JSON - extracting the HTML
       id and HTML content for each one. Replace the HTML currently at id
       with the new HTML content */
    
    if ( response.html ) {
        for ( var i = 0; i < response.html.length; i++ ) {
            var elem = document.getElementById( response.html[i].id );
            if ( elem ) elem.innerHTML = response.html[i].content;
        }
    }
    
    /* Execute any Javascript contained in the JSON */
    
    if ( response.js ) eval( response.js );
    
    /* If response includes modal flag set inputting global to true so
       that cannot edit any other widgets */
       
    inputting = response.modal ? true : false;
}

    
/*
 *  ocAjax - makes a OneClimate AJAX call
 *
 *   IN: url - AJAX request URL
 *   IN: id - HTML element id where AJAX response will be inserted
 */
function ocAjax( url, id ) {
    
    elemAjax = document.getElementById( id );
    
    oXml.open( 'GET', url, true );
    oXml.onreadystatechange = ocInsertAjaxResponse;
    oXml.send('');
}


/*
 *  ocAjaxAdmin - makes a OneClimate administration call by Ajax
 */
function ocAjaxAdmin( here, url, updateClass, updatingMsg ) {
    
    /* Check that we are not still awaiting a previous Ajax response */
    
    if ( elemAjax ) {
        alert( 'Another action is already in process ' +
               ' - please wait until that has finished' );
        return false;
    }
     
    /* use the class name to locate the element where Ajaz response will go,
       replace contents of that element with an updating message */
    
    var update = getParentByClass( here, updateClass );
    
    update.innerHTML = 
        '<img src="/wp-content/themes/OneClimateV3/images/loading.gif"/>' +
        '<span style="color: #000000;"> ' + updatingMsg + '...</span>';
        
    elemAjax = update;
    
    /* issue the Ajax request to the server */
    
    oXml.open( 'GET', url, true );
    oXml.onreadystatechange = ocInsertAjaxResponse;
    oXml.send('');
        
    return true;
}


/*
 *  getParentByClass - obtains parent of specified element which has the
 *                     specified class 
 *
 *   IN: element - element whose parent content area we want 
 *  RET: the content parent element
 */
function getParentByClass( element, reqdClass ) {

    if ( !( reqdClass instanceof RegExp ) ) 
	    reqdClass = new RegExp( reqdClass, 'i' ); 
    
    if ( element.className == undefined ) return undefined;
    
    if ( !reqdClass.test( element.className ) ) {
        return getParentByClass( element.parentNode, reqdClass );
    } else {
        return element;
    }
    
} 

function getParentByTag( element, reqdTag ) {
    
    if ( !( reqdTag instanceof RegExp ) ) 
	    reqdTag = new RegExp( reqdTag, 'i' ); 
    
    if ( element == undefined ) return undefined;

    if ( !reqdTag.test( element.nodeName ) ) {
        return getParentByTag( element.parentNode, reqdTag );
    } else {
        return element;
    }
}
    
/*
 *  ocAjaxRequest - makes an Ajax request
 *
 *   IN: url - the URL request to make in Ajax mode
 */
function ocAjaxRequest( url ) {

    oXml.open( 'GET', url, true );
    oXml.onreadystatechange = ocInsertAjaxResponse;
    oXml.send('');
}


/*
 * 
  - makes an Ajax form request. Submits post or get request to
 *               URL as defined in <form> element which is parent of element
 *               where Ajax request is made. Includes values of any
 *               <input> or <textarea> children of the <form> elenent
 *
 *   IN: element - HTML element object making this Ajax request
 *   IN: handler - function which will handle the Ajax response
 *   IN: updating - class of element under which to look for updating field
 *   IN: append - can be used to append extra name/value pairs
 */
function ocAjaxForm( element, handler, updating, append ) {
    
    var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
    
    var handler = handler || ocInsertAjaxResponse;
    var updating = updating || 'widget1';
    var append = append || null;
   
    updating = getParentByClass( element, updating );
    updating = getElementsByClassName( 'updating', null, updating );
    if ( updating != '')
        updating[0].className = removeClass( updating[0].className, 'hidden' );

    /* Locate the <iframe> element in which this Ajax request is being made */
    
    var form = getParentByTag( element, 'form' );
    if ( form == undefined ||
         form.getAttribute( 'method' ) == undefined ||
         form.getAttribute( 'action' ) == undefined ) {
        alert( 'Unable to submit request - web page incorrect' );
        return false;
    }
    
    /* First create post parameter of form submit=name where name is
       the HTML name attribute of element */ 
    
    content = new Array();
    var submit = element.getAttribute( 'name' );
    if ( submit ) content.push( 'submit' + '=' + submit );

    /* Loop through input, textarea and select children of form element 
       assembling name value pairs */
        
    var input = form.getElementsByTagName( 'input' );
    for ( var i = 0; i < input.length; i++ )
        if ( input[i].getAttribute( 'name' ) && input[i].value ) {
        	
        	if ('checkbox' == input[i].type.toLowerCase() ||
                'radio' == input[i].type.toLowerCase() ) {
        		
        		if (input[i].checked)
        		 content.push( input[i].getAttribute( 'name' ) + '=' + 
                          encodeURIComponent( input[i].value ) );
        		
        	} else {
            content.push( input[i].getAttribute( 'name' ) + '=' + 
                          encodeURIComponent( input[i].value ) );
            }
         }
    var input = form.getElementsByTagName( 'textarea' );
    
      
    for ( var i = 0; i < input.length; i++ ) {
    	
        if ( input[i].getAttribute( 'name' ) ) {
        	
        	// contents is the name of textarea field which contents come from an (tinymce) iFrame
        	  	     content.push( input[i].getAttribute( 'name' ) + '=' + 
                    encodeURIComponent( input[i].value ) );
        }
    
    }
    
    input = form.getElementsByTagName( 'select' );
    for ( var i = 0; i < input.length; i++ ) 
        content.push( input[i].getAttribute( 'name'  ) + '=' + 
                encodeURIComponent( 
                        input[i].options[input[i].selectedIndex].value ) );
        
    /* Append any extra name/value pairs if supplied */
    
    if ( append ) content.push( append );
                              
    /* Make Ajax request - post or get depending upon method parameter in
       <form> element */
       
    if ( form.getAttribute( 'method' ) == 'post' ) {        
        oXml.open( 'post', form.attributes['action'].value, true );        
        oXml.onreadystatechange = handler;
        oXml.setRequestHeader( 'Content-Type', contentType );
        oXml.send( content.join( '&' ) );
        
    } else {
        oXml.open( 'get', form.getAttribute( 'action' ) + 
                   ( content.length > 0 ? '?' : '' ) +
                     content.join( '&' ), true );
        oXml.onreadystatechange = handler;
        oXml.send( content.join( '' ) );    
    }
    
}



function owSubmitOnEnter( where, event ) { 
 
    if ( !event ) var event = window.event;
    
    if ( event.keyCode ) 
        var key = event.keyCode;
	else if ( event.which ) 
        var key = e.which;
    
    if ( key != 13 ) return true;
    
    var widget = getParentByClass( where, 'widget1' );
    elemAjax = widget;
    ocAjaxForm( where, owJSONHandler );
    
}

    
/*
 *  ocInsertAjaxResponse - places AJAX response in element specified in
 *                         elemAjax global variable (which is typically
 *                         specified when the Ajax request made
 */
function ocInsertAjaxResponse() { 
    
    if ( oXml.readyState != 4 ) return;  // our request is not done    
    
    if ( elemAjax ) {
        elemAjax.innerHTML = oXml.responseText;
        elemAjax = null;
        inputting = false;
    }
}


/*
 *  getElementsByClassName - returns nodes having specified class name
 *
 *   IN: className - name of class which retrieved nodes belong to
 *   IN: tag - optional - just return this kind of tag
 *   IN: elm - optional - search below this element
 *  RET: array of nodes in specified class
 *
 *   Written by Jonathan Snook, http://www.snook.ca/jonathan
 *   Add-ons by Robert Nyman, http://www.robertnyman.com
 *   Revised version May 11th 2007
 */
function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}	
	}
	return returnElements;
}


/*
 *  removeClass - remove specified class from space-separated list of classes
 *
 *   IN: classList - list of class names
 *   IN: remove - class to remove if presenr
 *  RET: class list with specified class removed
 */
function removeClass( classList, remove ) {
    remove = remove.toLowerCase();
    var work = classList.toLowerCase().split( ' ' );
    var result = '';
    for ( var i = 0; i < work.length; i++ ) 
        if ( work[i] != remove ) result += work[i] + ' ';
    return trim( result );
}



// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setFocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}


// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message) // string to display
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  // var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}


var proceed = 2;  

/*
 *  checkFunctionality - checks capability of browser and whether information
 *                       field present
 *
 *   IN: infoElem - element where information message will be written
 */
function checkFunctionality( infoElem ) {
    
    /* check browser supports getting element, element is present and is
       a text node */
    
    if ( !document.getElementById ) return true;  
    var elem = document.getElementById( infoElem );
    if ( !elem.firstChild ) return true; 
    if ( elem.firstChild.nodeType != node_text ) return true;  

    return proceed;
}

/*
 *  validateSearch - check search text value
 *
 *   IN: valElem - element to be validated
 *   IN: infoElem - element where informational message to be placed
 */
function validateSearch( valElem, infoElem ) {
    
    var stat = checkFunctionality( infoElem );
    if ( stat != proceed ) return stat;

    var value = trim( valElem.value );  
    var initial = document.getElementById( 'initial' ).value;
    
    if ( emptyString.test( value ) || value == initial ) {
        msg( infoElem, 'error', 
             document.getElementById( 'SPMsgNoText' ).value );
        setFocus( valElem );
        return false;
    }
    
    if ( value.length < 3 ) {
        msg( infoElem, 'error', 
             document.getElementById( 'SPMsgTooShort' ).value );
        setFocus( valElem );
        return false;
    }

    document.search.action += valElem.value;
    // document.search.method = 'post';
    
    return true;
}


function checkBrowserWidth()
{
	var theWidth = getBrowserWidth();
	
	if (theWidth == 0)
	{
		var resolutionCookie = document.cookie.match(/(^|;)tmib_res_layout[^;]*(;|$)/);

		if (resolutionCookie != null)
		{
			setStylesheet(unescape(resolutionCookie[0].split("=")[1]));
		}
		
		addLoadListener(checkBrowserWidth);
		
		return false;
	}

	if ( theWidth > 1220 ) {
		setStylesheet("widescreen");
		document.cookie = "tmib_res_layout=" + escape("widescreen");
	} else if ( theWidth <= 800 ) {
		setStylesheet("smallscreen");
		document.cookie = "tmib_res_layout=" + escape("smallscreen");        
    } else {
		setStylesheet("");
		document.cookie = "tmib_res_layout=";
	}
	
	return true;
};




function getBrowserWidth()
{
	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;
	}
	
	return 0;
};




function setStylesheet(styleTitle)
{
	var currTag;

	if (document.getElementsByTagName)
	{
		for (var i = 0; (currTag = document.getElementsByTagName("link")[i]); i++)
		{
			if (currTag.getAttribute("rel").indexOf("style") != -1 && currTag.getAttribute("title"))
			{
				currTag.disabled = true;

				if(currTag.getAttribute("title") == styleTitle)
				{
					currTag.disabled = false;
				}
			}
		}
	}
	
	return true;
};


function addLoadListener(fn)
{
	if (typeof window.addEventListener != 'undefined')
	{
		window.addEventListener('load', fn, false);
	}
	else if (typeof document.addEventListener != 'undefined')
	{
		document.addEventListener('load', fn, false);
	}
	else if (typeof window.attachEvent != 'undefined')
	{
		window.attachEvent('onload', fn);
	}
	else
	{
		return false;
	}
	
	return true;
};




function attachEventListener(target, eventType, functionRef, capture)
{
    if (typeof target.addEventListener != "undefined")
    {
        target.addEventListener(eventType, functionRef, capture);
    }
    else if (typeof target.attachEvent != "undefined")
    {
        target.attachEvent("on" + eventType, functionRef);
    }
    else
    {
        return false;
    }

    return true;
};





function toPassword( oldObject ) {
  var newObject = document.createElement('input');
  newObject.type = 'password';
  if(oldObject.size) newObject.size = oldObject.size;
  if(oldObject.value) newObject.value = '';
  if(oldObject.name) newObject.name = oldObject.name;
  if(oldObject.id) newObject.id = oldObject.id;
  if(oldObject.className) newObject.className = oldObject.className;
  oldObject.parentNode.replaceChild(newObject,oldObject);
  newObject.select();
  newObject.focus();
  return newObject;
}

function createCookie(name,value,days,host) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	
	if (host) {
		
		var domain = "; domain="+ host ;
	
	} else {
		
			var domain ="";
		
	}
	// alert (name+"="+value+expires+domain+"; path=/");
	document.cookie = name+"="+value+expires+domain+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = 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 eraseCookie(name) {
	createCookie(name,"",-1);
}

/*  Create an ow namespace for all OneWorld methods */

var ow = ow || {};

/*  Define functions associated with Ajax request  */

ow.ajax = {
    
    /*  Make an Ajax request to the specified URL */
    
    url:   function( url ) {
        oXml.open( 'GET', url, true );
        oXml.onreadystatechange = owJSONHandler;
        oXml.send('');    
    
        return false;
    },    
    
    /*  Submit form */
    
    submit: function( elem, clicked) {
    	if (typeof tinyMCE != 'undefined' )
    		tinyMCE.triggerSave();
    	var append = clicked === undefined ? null : 'clicked=' + clicked;
        ocAjaxForm( elem, owJSONHandler, 'mwidget', append );
        return false;
    },
    
    widget: function( id, args ) {
        
        var args = args ? args : '';
        args += '&jq=y';
    
        var widget = $( '#' + id );
        var url = '/ajax/' + widget.attr( 'class' ).substr( 8 ) + '?config=' +
                  widget.find( 'input[name=config]' ).attr( 'value' ) + args;
        $.getJSON( url, function( data ) {
            for ( var i in data.html )
                $( '#' + data.html[i].id ).html( data.html[i].content );
            if ( data.js !== undefined ) eval( data.js );
        } );
    }
}

ow.base = {
    
    buttonHover:   function() {
        $( '.mbutton' ).hover( 
            function() {
                $( this ).addClass( 'hover' );
            },
            function() {
                $( this ).removeClass( 'hover' );
            }         
        );
    },
    
    link:   function( href, text ) {
        return '<a target="_blank" href="' + href + '">' + text + '</a>';
    },
    
    /**
     *  Perform login actions
     *
     *  @param  string  name name of the user
     *  @param  boolean isAdmin whether user is administrator or not
     *  @param  boolean closePopup whether to close popup
     */
    login:  function( name, isAdmin, closePopup ) {
        
        var closePopup = closePopup === undefined ? true : closePopup;
        
        parent.$( '.tab-login' ).addClass( 'hidden' );
        parent.$( '.new-menu-widget .tab-profile' ).removeClass( 'hidden' );
        parent.$( '.site-user' ).removeClass( 'hidden' );
        parent.$( '.site-user span' ).text( name );
        if ( isAdmin )
            parent.$( '.site-user a.admin' ).removeClass( 'hidden' );
        else
            parent.$( '.site-user a.admin' ).addClass( 'hidden' );
        if ( closePopup ) parent.$.fancybox.close();
    },
    
    logout: function() {
        $( '.new-menu-widget .tab-profile' ).addClass( 'hidden' );
        $( '.tab-login' ).removeClass( 'hidden' );
        $( '.site-user' ).addClass( 'hidden' );
    },
        
    
    browseInit: function () {
        $( 'input.file' ).change( function() {
            var file = $( this ).val();
            $( this ).parents( 'div.browse' ).
                                children( 'input[type=text]' ).val( file );
        } );
    },

    popup:  function( url, width, height ) {
        
        var width = width ? width : 560;
        var height = height ? height : 350;
    	
        $.fancybox( {
				'width'				: width,
				'height'			: height,
				'padding'           : 0,
				'margin'            : 0,
				'autoScale'			: false,
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe',
				'href'              : url
		} );
    },
    
    /*
     *  Used to initialise a map when being added to a layout. Needs to
     *  be loaded before Google Maps loaded so included in base object */
     
    mapInit:   function() {
        var url = $( '#map-init' ).attr( 'value' );
        $( '#map-init' ).remove();
        ow.ajax.url( url );
    },
    
    registerPopup: function (elm, strUrl) {
    	var url = strUrl + elm.value;
    	ow.base.popup(url);
    },

    /**
     *  Determines whether running in a Safari browser, and therefore whether
     *  form submissions can be Ajax or not
     *
     *  @param  string  id widget identifier
     */
    isSafari: function( id ) {
        var safari = navigator.userAgent.search( /safari/i ) !== -1 &&
                     navigator.userAgent.search( /chrome/i ) === -1
                     ? 'true' : 'false';
        // alert( 'Is safari: ' + safari );
        $( '#' + id + ' input[name=non-ajax]' ).val( safari );
    },
    
    /**
     *  Clears a text input field ( input or textarea ) on focus, if it
     *  is showing the field's prompt
     */
    onFocus: function( where ) {
        
        
        /*  Locate the parent field div, and then the hidden prompt field */
        
        var where = $( where );
        var prompt = where.parent( 'div.field' ).
                        find( 'input[type=hidden]' ).first().attr( 'value' );
                        
        /* Determine tagName - either input or textarea */
        
        var tagName = where.attr( 'tagName' ).toLowerCase();
        
        /*  If value is prompt then clear input/textarea */
        
        if ( tagName === 'input' && $( where ).attr( 'value' ) === prompt )
            $( where ).attr( 'value', '' );
        else if ( tagName === 'textarea' && $( where ).val() === prompt )
            $( where ).val( '' ); 
    },
    
    /**
     *  Submit form (non-ajax) containing element, optionally modifying
     *  the action parameter
     *
     *  @param  HTMLElement where - element contained by form
     *  @param  string action - overrides <form> action value
     */
    submit: function( where, action ) {
        
        var form = $( where ).parents( 'form' );
        if ( action !== undefined ) form.attr( 'action', action );
        form.submit();
    }
    
}

ow.dialog = {
    
    /* Open dialog box, enabling it first if necessary */
    
    open:   function() {
        if ( !$('#dialog').is(':data(dialog)') )
            $( '#dialog' ).dialog( 
                            { modal : true, autoOpen: false, width: 'auto' } );
        $( '#dialog' ).dialog( 'open' );
    },
    
    close: function() {
        $( '#dialog' ).dialog( 'close' );
    }
}

ow.slider = {
    
    init:   function( id, numPages, url ) {
        $( '#' + id + '-slider' ).slider( { min: 1, max: numPages,
                change: function( event, ui ) { 
                    ow.ajax.url( url + ui.value ); 
                    $( '#' + id + '-slider > .updating' ).show();
                } 
        } );
    }, 
    
    show:   function( id ) {
        $( '#' + id + '-slider > .updating' ).hide();
    }
}
    
ow.layout = {
    
    init:   function() {
        $( '#widget-layout-0-0' ).slideDown( 'slow' );
		$( '#main .mwidget > .wcontent' ).fadeTo( 'slow', 0.5 );
		$( '#main .mwidget > .configure' ).fadeIn( 'slow' );
		$( '#main .mwidget' ).draggable( { containment: '#main', grid: [240, 10], 
		                        opacity: 0.5, zIndex: 100, cursor: 'move' } );
		$( '#main' ).css( { 'border': '#dfdfdf 15px solid',
		                    'border-top-width': '0px' } );
		$( '#main' ).resizable( );
    },

    /**
     *  Saves a layout
     *
     *  @param  boolean draft   whether save as draft or publish as live
     *  @param  int     version version number of layout being edited
     */
    save:   function( draft, version ) {
        
        var draft = draft === undefined ? false : draft;
        var version = version === undefined ? null : version;
        
        var layout = new Array();
        $( '#main > .mwidget' ).each( function() {
            var widget = $( this );
            var configId = widget.children( 'input.config-id' ).attr( 'value' );
            if ( configId !== null )
                layout.push( widget.attr( 'id' ) + ';' + configId + ';' + 
                             Math.round( widget.position().top ) + ';' + 
			                 Math.round( widget.position().left ) + ';' + 
			                 widget.width() + ';' + widget.height() ); 
			} );
		layout = '&layout=' + encodeURIComponent( layout.join( ':' ) );
		
        oXml.open( 'post', '/ajax/widget-layout', true );        
        oXml.onreadystatechange = owJSONHandler;
        oXml.setRequestHeader( 'Content-Type', 
                        'application/x-www-form-urlencoded; charset=UTF-8' );
        /* DIAG alert( '/ajax/widget-layout?config=0:0:0:' + 
                   ( draft ? 'draft' : 'publish' ) + 
                   decodeURIComponent( layout ) + '&path=' + 
                   window.location.pathname  +
                   ( version === null ? '' : '&version=' + version ) ); */
        oXml.send( 'config=' + encodeURIComponent( '0:0:0:' ) + 
                   ( draft ? 'draft' : 'publish' ) + layout + '&path=' + 
                   encodeURIComponent( window.location.pathname ) +
                   ( version === null ? '' : '&version=' + version ) );
		
    },
    
    redrawWidget:   function( id, width, height ) {
        $( '#dialog' ).dialog( 'close' );
        $( '#' + id ).width( width );
        $( '#' + id ).height( height );
		$( '#' + id + ' > .wcontent' ).fadeTo( 'slow', 0.5 );
		$( '#' + id + ' > .configure' ).fadeTo( 'slow', 1.0 );
		$( '#' + id ).draggable( { containment: '#main', grid: [240, 10], 
		                        opacity: 0.5, zIndex: 100, cursor: 'move' } );     
	},
    
    listWidgets:      function() {
        $( "div.buttons > img[src*='add']" ).hide();
        $( 'ul.widgets > li' ).removeClass( 'selected' );
        $( 'ul.widgets' ).slideToggle( 'slow' );
        $( "div.buttons > img[src*='cancel']" ).click( function() {
                $( 'ul.widgets' ).slideUp( 'slow' );
        } );
        $( "div.buttons > img[src*='add']" ).click( function( event ) {
                ow.layout.addWidget();
        } );
        $( 'ul.widgets > li' ).click( function() {
                $( 'ul.widgets > li' ).removeClass( 'selected' );
                $( this ).toggleClass( 'selected' );
                $( "div.buttons > img[src*='add']" ).show();
        } );
    },
    
    showHistory:    function() {
        $( 'ul.history' ).slideToggle( 'slow' );
        $( "div.buttons > img[src*='cancel']" ).click( function() {
                $( 'ul.history' ).slideUp( 'slow' );
        } );
    },
    
    addWidget: function() {
        
        /* Identify selected widget from HTML class of selected <li> element,
           and un-select this <li> ready for next time list shown */
        
        var widget = $( 'ul.dropdown > li.selected' );
        if ( widget == null ) return;
        widget.removeClass( 'selected' );
        widget = widget.attr( 'class' 
                            ).replace( 'selected', '' ).replace( ' ', '' );
                            
        /* See if CSS stylesheet for this widget already loaded - if not
           then load it by adding <link> element into <head> part of page */
           
        var css = widget.split( '-' );
        for ( i in css )
            css[i] = css[i].substr( 0, 1 ).toUpperCase() + css[i].substr( 1 );
        css = css.join( '' ) + '.css';
        if ( !$( "head > link" ).is( "link[href*='" + css + "']" ) ) 
            $( 'head' ).append( '<link rel="stylesheet" type="text/css" ' +
                 'href="/wp-content/themes/OneClimateV3/css/' + css + '"/>' );
        
        /* Construct unique HTML id for new widget container and add empty
           container to #main layout area */
           
        var time = new Date();
        time = time.getTime() % 100000000;
        var container = '<div id="' + widget + '-' + time + 
                        '-0" class="mwidget ' + widget + '" style="' +
                        'position: absolute; top: 0px; left: 0px; ' +
                        'width: 10px; height: 20px;"></div>';
        $( '#main' ).append( container );
        
        /* Submit Ajax request to add specified widget to layout, and slide up
           the widget dropdown list */
        
        ow.ajax.url( '/ajax/' + widget + '?config=0:' + time + ':0:add' );
        $( 'ul.dropdown' ).slideUp( 'slow' );
    },
    
    removeWidget: function( id ) {
        $( '#' + id ).fadeOut( 2000, function() { $( this ).remove(); } );
    },
    
    
    /*  Initialise the widget edit form so that hint text shown as user enters
        an input field */
        
    initForm:   function( id ) {
       $( 'div.field' ).mouseenter( 
            function() { 
                var div = $(this).find( 'div.hint' );
                if ( div.html() == '' ) {
                    var hint = $(this).find( 'input.hint' ).attr( 'value' );
                    if ( hint != null ) div.html( hint );
                }
            } );
        $( 'div.field' ).mouseleave( 
            function() { 
                var div = $(this).find( 'div.hint' );
                div.html( '' );
            } );
        ow.dialog.open();

    }
}

ow.menu = {
    
    /*  Initialises the menu widget */
    
    init: function() {
        
        /*  Function called when entering tabs except current & login one
            which turns on hover styles */
        
        $( '.new-menu-widget .tab' ).
            not( '.tab-selected, .tab-login, .tab-profile' ).mouseenter( 
                function() { 
                    ow.menu.hoverOff();
                    $( this ).addClass( 'tab-hover' );  
                    $( '.tab-selected' ).addClass( 'tab-selected-off' );
                    $( '#btm-' + this.id.slice( 4 ) ).removeClass( 'hidden' );
                    $( '.selected' ).addClass( 'hidden' );
                } );
         
         /* Turn hover styles off when leaving or entering specific zones */
         
         $( '.menu, .bottom' ).mouseleave( 
             function() { ow.menu.hoverOff(); } );
         $( '.tab-selected, .tab-login' ).mouseenter( 
             function() { ow.menu.hoverOff(); } );
         
         /* Define function called when search button append */
         
         $( '.new-menu-widget .search .button' ).click( function() {
             $( this ).addClass( 'append' );
         } );
             
         /* Define function when entering site tab which reveals site
            wide menu */
         
         $( '.new-menu-widget .site-menu-tab' ).mouseenter( function() {
             $( '.new-menu-widget .site-menu' ).slideDown( 'slow' );
         } );
         
         /* Define function which closes site wide menu */
         
         $( '.new-menu-widget .site' ).mouseleave( function() {
             $( '.new-menu-widget .site-menu' ).delay( 2000 ).slideUp( 'slow' );
         } );
         
         $( '.new-menu-widget .tab-login' ).click( function() {
                 ow.base.popup( '/mwidget/register-widget?config=0:0:0:login' );
         } );
         
         
    },
    
    /**
     *  Unsets all changes made when hovered over a top row tab
     */
    hoverOff: function() {
        $( '.tab-hover' ).removeClass( 'tab-hover' ); 
        $( '.tab-selected-off' ).removeClass( 'tab-selected-off' );
        $( '.bottom' ).addClass( 'hidden' );
        $( '.selected' ).removeClass( 'hidden' );
    }
     
}

ow.getElm = {
		
		findIframe : function () {
			var textarea = '';
			var myIFrame = document.getElementById('content_ifr');
			alert('b');
	    	if (myIFrame){
				textarea = myIFrame.contentWindow.document.body.innerHTML; 
				alert('c');
			}
			alert(textarea);
		
		}
}

/* function to create an instance of tinymce editor and initialise it with chocen options */
ow.richTxt = {
	toggleEditor : function (id) {
	       
			if (!tinyMCE.get(id)) {
			    tinyMCE.init({
				mode : "specific_textareas",
			    editor_selector: "wysiwyg",
				theme : "advanced",
			    relative_urls: false,
			    plugins: "media,preview,safari,owimage,owvideo,paste",
			    theme_advanced_buttons1: "undo, redo, |, bold, italic, underline, |, bullist, numlist, |, cut, copy, paste, pasteword, |, link, unlink, |, preview, |, code, |, owimage, |, owvideo",
			    theme_advanced_buttons2: "forecolor, backcolor, |, fontselect, fontsizeselect, |, outdent, indent, |, justifyleft, |, justifycenter, |, justifyright, |, justifyfull, |, hr",
			    theme_advanced_buttons3: "removeformat, visualaid, |, sub, sup, |, charmap",
			    theme_advanced_toolbar_location : "top",
			    theme_advanced_toolbar_align: "left",
				theme_advanced_statusbar_location : "bottom",
			    theme_advanced_resizing: true,
			    theme_advanced_resize_horizontal: false,
			    extended_valid_elements: "div[class|id]",
			    media_strict: false,
			    plugin_preview_width: "680",
			    plugin_preview_height: "600",
			    content_css : "/wp-content/themes/OneClimateV3/style.css"
					});
		   } else {
					tinyMCE.execCommand('mceRemoveControl', false, id);
		   }	
		},
		
		initEditor : function (id) {
		           
			       if (id == 'job') {
			    	   	  tinyMCE.init({
			    		   mode : "specific_textareas",
			    		   editor_selector: "wysiwyg",
			    		   theme : "advanced",
			    		   relative_urls: false,
			    		   plugins: "media,preview,safari,owimage,owvideo,paste",
			    		   theme_advanced_buttons1: "bold, italic, underline, |, bullist, numlist, |, pasteword, |, link, unlink, |, preview, |, code",
			    		   theme_advanced_buttons2: "",
			    		   theme_advanced_toolbar_location : "top",
			    		   theme_advanced_toolbar_align: "left",
			    		   theme_advanced_statusbar_location : "bottom",
			    		   theme_advanced_resizing: true,
			    		   theme_advanced_resize_horizontal: false,
			    		   extended_valid_elements: "div[class|id]",
			    		   media_strict: false,
			    		   plugin_preview_width: "680",
			    		   plugin_preview_height: "600",
			    		   content_css : "/wp-content/themes/OneClimateV3/style.css"
					});
			       } else {
			    	   		tinyMCE.init({
					    	mode : "specific_textareas",
					        editor_selector: "wysiwyg",
							theme : "advanced",
					        relative_urls: false,
					        plugins: "media,preview,safari,owimage,owvideo,paste",
					        theme_advanced_buttons1: "bold, italic, underline, |, bullist, numlist, |, pasteword, |, link, unlink, |, preview, |, code, |, owimage, |, owvideo",
					        theme_advanced_buttons2: "",
					        theme_advanced_toolbar_location : "top",
					        theme_advanced_toolbar_align: "left",
							theme_advanced_statusbar_location : "bottom",
					        theme_advanced_resizing: true,
					        theme_advanced_resize_horizontal: false,
					        extended_valid_elements: "div[class|id]",
					        media_strict: false,
					        plugin_preview_width: "680",
					        plugin_preview_height: "600",
					        content_css : "/wp-content/themes/OneClimateV3/style.css"
			    	 }); 
			       }
		}
}


		
		
/*  Functions associated with error messages    */

ow.error = {
    
    /*  Clear all error messages by clearing all content in <span> and <div>
        elements with class "error" */
        
    clearAll:   function() {
        var msgs = getElementsByClassName( 'error', 'span' );
        for ( var i = 0; i < msgs.length; i++ ) msgs[i].innerHTML = '';
        var msgs = getElementsByClassName( 'error', 'div' );
        for ( var i = 0; i < msgs.length; i++ ) msgs[i].innerHTML = '';
    }
}

ow.confirm = {

	b4Run: function (fn,txt)
	{
 		var where_to= confirm(txt);
 		if (where_to== true) {
   			eval(fn);
 		}
 
	}
}  

ow.form = {
	         
	   /*  Normal form submit */
	    submit: function( elem ) {
			var form = getParentByTag( elem, 'form' );
			form.submit();
	    },
		
	    /* cancel form submit and redirect to the location given */
		cancel: function (location){
	       	window.location = location;
	    }	
		


}

ow.field = {
    
    initial: [],                        // holds initial values of fields
    
    /**
     *  Specified fields whose values should be changed. These fields
     *  will be cleared on focus, but returned to their original value
     *  if the user does not supply a new value for them.
     *
     *  @param  string selector jQuery selector specifying "must change" elems
     */
    mustChange: function( selector ) {
        $( selector ).each( function() {
            ow.field.initial[$( this ).attr( 'name' )] = undefined;
        } );
        $( selector ).focusin( function() {
            var name = $( this ).attr( 'name' );
            if ( ow.field.initial[name] === undefined ) {
                ow.field.initial[name] = $( this ).val();
                $( this ).val( '' );
            }
        } );
        $( selector ).focusout( function() {
            var name = $( this ).attr( 'name' );
            if ( $( this ).val().replace( /\s/g, '' ) === '' ) {
                $( this ).val( ow.field.initial[name] );
                ow.field.initial[name] = undefined;
            }
        } );
    }, 
    
    /**
     *  Register event handling functions for file upload fields
     *
     *  @param  string  form jQuery selector for upload form 
     *  @param  string  result jQuery selector for input result field
     *  @param  string  prepend text to insert before file name
     */
    initUpload: function( form, result, prepend ) {
        
        var prepend = prepend === undefined ? 'File: ' : prepend;
        
        /*  Upload file when input file element changed */
        
        $( form + ' input' ).change( function() {
            $( form + ' div.uploading' ).fadeIn( 'slow' );
            $( form + ' div.selected' ).html( 'File: no image selected' );
            $( result ).val( '' );
            $( form ).submit();
        } );
        
        /*  Check and process response from file upload */
        
        $( form + ' iframe' ).load( function() {
            $( form + ' div.uploading' ).fadeOut( 'slow' );
            var response =  $( this ).contents().find( 'body' );
            var msg = response.text();
            response = response.html();
            var resultType = $( result ).attr( 'tagName' ).toLowerCase();
            $( form + ' input' ).val();
            if ( response && msg.substr( 0, 7 ) === 'myfile:' ) {
                $( form + ' div.selected' ).
                                        html( 'File: no image selected' );
                $( form + ' div.error' ).html( mag.substr( 7 ) );
                if ( resultType === 'input' )
                    $( result ).val( '' );
                else
                    $( result ).html( );
            } else if ( response !== '' ) {
                $( form + ' div.selected' ).html( prepend + msg );
                $( form + ' div.error' ).html( '' );
                if ( resultType === 'input' )
                    $( result ).val( msg );
                else
                    $( result ).html( response );
            }
        } );

    }
    
}

