var junk = ( navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('Mac') != -1 );
var gecko = ( navigator.userAgent.indexOf('Gecko') != -1 );
var isIE =  ( navigator.userAgent.indexOf('MSIE') != -1 );
var Safari = ( navigator.userAgent.indexOf('KHTML') != -1);
var adDataSettings = new Object ();
var advert_code = new Object();
var eventHolder = new Object;
eventHolder['run'] = null;
var startRange;
var rangeCount;

function get_page_ad_source()
{
    var source = '';
	var doc = document;

    if ( doc.location == null ) { return 's1learning-global' }

    if ( doc.location.hostname.indexOf('s1learning') != -1 )
	{
	    source = 's1learning-';
	    var testRE = new RegExp ( "(/[^/]*/?)", "i" );
	    switch ( doc.location.pathname.match(testRE)[0] )
		{
			case "/" :  source += 'home'; return source;
			case "/index.shtml" :  source += 'home'; return source;
			case "/degree/" : source += 'degree'; return source;
            case "/academic/" : source += 'academic'; return source;
			case "/vocational/" : source += 'vocational'; return source;
			case "/post-graduate/" : source += 'post-graduate'; return source;
			case "/recreational/" : source += 'recreational'; return source;

			default: return 's1learning-global';
		}
	}



    var testRE = new RegExp( "^/([^/]+/)?(index.s?html)?$" );
    if ( doc.location.pathname.match(testRE) )
	{
	    source += 'home';
	}
    else if ( ! ( doc.location.search && doc.location.search.indexOf( 'location' ) != -1 ) )
	{
	    source += 'global';
	}

	 if ( doc.location.pathname.indexOf('search') != -1 )
	{
	   source = 's1learning-';
	   var thisURL = doc.location.search;
	   var thisURL = thisURL.replace(/^.*general_subject_area=([^&;]+).*$/, "$1");
	    if (thisURL && thisURL != "")
        thisURL = thisURL.replace(/[^a-z0-9]+/ig, "_");
		if (thisURL && thisURL != "")
	    source +=  thisURL;
	}

    if(source == '') { source = 's1learning-global'; }

    return source;

}




function showMoreOptions()
{
		document.getElementById('moreOptions').style.display = "block";
		document.getElementById('moreOptionsLink').style.display = "none";
}

function checkFriend()
{
	var themessage = "Please enter at least:\n";

	if ((document.form1.email.value.indexOf('@') < 1) || (document.form1.email.value.length < (document.form1.email.value.indexOf('@') + 5)) )
	{
		themessage = themessage + " - Your friend\'s email address\n";
	}

	if (document.form1.name.value=="")
	{
		themessage = themessage + " - Your friend\'s name\n";
	}

	if (document.form1.member_name.value=="")
	{
		themessage = themessage + " - Your name\n";
	}

	//alert if fields are empty and cancel form submit

	if (themessage == "Please enter at least:\n")
	{
		return true;
	}
	else
	{
		alert(themessage);
		return false;
	}
}

function showDegree()
{
  document.getElementById('searchDegreebox').style.display = "inline";
  document.getElementById('searchPrivatebox').style.display = "none";
  document.getElementById('searchVocationalbox').style.display = "none";
  document.getElementById('searchPosgradbox').style.display = "none";
}

function showPostgrad()
{
  document.getElementById('searchPosgradbox').style.display = "inline";
  document.getElementById('searchPrivatebox').style.display = "none";
  document.getElementById('searchVocationalbox').style.display = "none";
  document.getElementById('searchDegreebox').style.display = "none";
}

function showVocational()
{
  document.getElementById('searchVocationalbox').style.display = "inline";
  document.getElementById('searchPrivatebox').style.display = "none";
  document.getElementById('searchPosgradbox').style.display = "none";
  document.getElementById('searchDegreebox').style.display = "none";
}

function showPrivate()
{
  document.getElementById('searchPrivatebox').style.display = "inline";
  document.getElementById('searchPosgradbox').style.display = "none";
  document.getElementById('searchVocationalbox').style.display = "none";
  document.getElementById('searchDegreebox').style.display = "none";
}


function ShowInstDetails()
{
  if(document.mainform.institution_name.options[document.mainform.institution_name.selectedIndex].value)
  {
    document.getElementById('institution_details').style.display = "inline";
  }
  else
  {
    document.getElementById('institution_details').style.display = "none";
  }
}

function prePopulateInstitutionDetails()
{

    if ( window.ActiveXObject ) // if it's ie
    {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {
          if(xmlhttp.readyState == 4) writecontent(xmlhttp.responseText);
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writecontent(xmlhttp.responseText) };
       }
       else return; //
    }

	if(document.mainform)
	{
	 var institution_name = document.mainform.institution_name.options[document.mainform.institution_name.selectedIndex].value;
	 if(institution_name == "")
	 {
	   var institution_name = document.mainform.inst_name.value;

	 }

	}


	var targ = document.getElementById('institution_details').style.display = 'block';
	if(institution_name != "")
	{

	   var url = "http://" + document.location.hostname + "/coursemanager/get_institution_details.cgi?name=" + institution_name;

       xmlhttp.open("GET", url , true);
       xmlhttp.send(null);
	}
	else
	{
	   document.getElementById('institution_details').style.display = 'none'
	}
}

function writecontent (content)
{
     document.getElementById('institution_details_content').innerHTML = content;
}


function prePopulateSubSectors()
{

    if ( window.ActiveXObject ) // if it's ie
    {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {
          if(xmlhttp.readyState == 4) writesscontent(xmlhttp.responseText);
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writesscontent(xmlhttp.responseText) };
       }
       else return; //
    }

		if(document.stepOne)
		{
		 var sector_id = document.stepOne.general_subject_area.options[document.stepOne.general_subject_area.selectedIndex].value;
		}

	   if(document.stepOne.general_subject_area)
	   {
		   var url = "http://" + document.location.hostname + "/get_sub_sectors.cgi?sector_id=" + sector_id;

		   xmlhttp.open("GET", url , true);
		   xmlhttp.send(null);
	   }

}

function writesscontent (content)
{
    var targs = getElementsByClass('sub_sectors_area');
    for( i=0; i < targs.length; i++)
	{
	 targs[i].innerHTML = content;
    }
}



function prePopulateMappedSubSectors(count)
{

    if ( window.ActiveXObject ) // if it's ie
    {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {
          if(xmlhttp.readyState == 4) writemapcontent(xmlhttp.responseText, count);
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writemapcontent(xmlhttp.responseText, count) };
       }
       else return; //
    }

		if(document)
		{
		 var targ = document.getElementById('s1_mapping_' + count);
		 if(targ)
		 {
		   var sector_id = targ.options[targ.selectedIndex].value;
		 }
		}

	   if(sector_id)
	   {
		   var url = "http://" + document.location.hostname + "/get_sub_sectors.cgi?number=" + count + "&sector_id=" + sector_id ;
		   xmlhttp.open("GET", url , true);
		   xmlhttp.send(null);
	   }

}

function writemapcontent (content, count)
{
    var targ = document.getElementById('s1_sub_mapping_' + count);
	if(targ)
	{
	  targ.innerHTML = content;
    }
}


function showAddInstDetails()
{
  document.getElementById('add_institution_details').style.display = "inline";
  document.getElementById('institution_details').style.display = "none";
  document.getElementById('institution_name').style.display = "none";
}

function closeAddInstDetails()
{
  document.getElementById('add_institution_details').style.display = "none";
  document.getElementById('institution_details').style.display = "inline";
  document.getElementById('institution_name').style.display = "inline";
}

function sortedby_redirect()
{
 var searchparams =document.mainform.searchparamsnosort.value;
 var url;

 if(searchparams != "")
 {
    if(document.minimainform)
    {
        var url = "/course_search.cgi?" + searchparams + "&sorted_by=" + document.minimainform.sorted_by.options[document.minimainform.sorted_by.options.selectedIndex].value;
 document.location.href=url;
    }
   else
    {
        var url = "/course_search.cgi?" + searchparams + "&sorted_by=" + document.mainform.sorted_by.options[document.mainform.sorted_by.options.selectedIndex].value;
 document.location.href=url;
    }
 }
}

function custom_sortedby_redirect()
{
    var searchparams =document.mainform.searchparamsnosort.value;
    var url;
    if(searchparams != "")
    {
        var url = document.location.pathname + "?" + searchparams + "&sorted_by=" + document.mainform.sorted_by.options[document.mainform.sorted_by.options.selectedIndex].value;
 document.location.href=url;
    }
}

function hide_target( t ) { t.style.visibility = 'hidden' }
function focus_target( t ) { t.focus() }
function show_target( t ) { t.style.visibility = 'visible' }
function show_target_nospace( t ) { t.style.display = 'block' }
function hide_target_nospace( t ) { t.style.display = 'none' }


function init_range( )
{
   range_init = false;

   if ( range_init ) { return true }
   range_init = true;

   writeRange( start, count );

}

var maxResults   = 10; // per page

function writeRange(start, maxCount )
{
  var target = document.getElementById('rangeBlock');
  if ( ! target || ! rangeCount || ! start || ( rangeCount < maxResults ) || maxCount > 40000)
  {
        var target1 = document.getElementById('pageSelect');
		if(target1)
		{
		  target1.style.display = 'inline';
        }
		return false;
  }

  var select = document.createElement('select');
  select.name='base';

  var target1 = document.getElementById('pageSelect');
  hide_target_nospace(target1);

  clean(target);

  addEvent(select,'change', search_range_redirect);

  target.appendChild(select);

  var counter = 1;

  for ( 1; counter <= maxCount; counter = counter + maxResults )
  {
    var exit = ( counter + maxResults ) - 1;
    if ( exit >= maxCount ) { exit = maxCount }

	var opt;
	if(counter < 4000)
	{
		opt = new Option( counter + ' to ' + exit, counter );
		if ( counter == exit ) opt = new Option( counter , counter );
    }
	else
	{
		return;
	}


    select.options[select.options.length] = opt;
    if ( counter == start )
    {
        select.options[select.options.length -1].selected = true;
    }
  }

}


function setMyDetails()
{
	var isIE =  ( navigator.userAgent.indexOf('MSIE') != -1 );
	var main_target = document.getElementById('searchResults');

	if ( document.getElementById('myDetails').offsetHeight < main_target.offsetHeight )
	{
		if ( isIE )
		{
			document.getElementById('myDetails').style.height = main_target.offsetHeight + 'px';
		}
		else
		{
    		document.getElementById('myDetails').style.minHeight = main_target.offsetHeight + 'px';
		}
	}
}

function popper( e )
{
    var targ = get_event_target( e );

    if ( targ.nodeName == 'IMG' ) { targ = targ.parentNode }

    if ( ! targ.href ) { return true }

    var width=300;
    var height=300;
    var scroll='yes';
    if ( targ.rel )
	{
	    var size = targ.rel.match(/^(pop.+) (.+$)/);
	    if ( size )
		{
		    var tmp = size[2].split(/x/);
		    width = tmp[0];
		    height = tmp[1];
		    if ( size[1] == 'popad' ) { scroll = 'no' }
		}

	}

    var left = 800 - width;
    var top = 600 - height;

    window.open(targ.href,'help','width='+width+',height='+height+',left='+left+',top='+top+',screenX='+left+',screenY='+top+',scrollbars='+scroll);

    return false;
}

function get_event_target( e )
{
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    return targ;

}

function addEvent(oTarget, sType, fpDest) {
  sType = 'on'+sType;
  var oOldEvent = oTarget[sType];
  if (typeof oOldEvent != "function") {
    oTarget[sType] = fpDest;
  } else {
    oTarget[sType] = function(e) {
      oOldEvent(e);
      fpDest(e);
    }
  }
}

function delCookie (NameOfCookie)
{
 // The function simply checks to see if the cookie is set.
 // If so, the expiration date is set to Jan. 1st 1970.
  if (Get_Cookie(NameOfCookie))
  {
   var cookie_date = new Date ( );  // current date & time
   cookie_date.setTime ( cookie_date.getTime() - 1 );
   document.cookie = NameOfCookie += "=; expires=" + cookie_date.toGMTString();
  }
}

function Get_Cookie( name )
 {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) &&
	( name != document.cookie.substring( 0, name.length ) ) )
	{
	return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}


 function createCookie()
 {
  var ExpireDate = new Date ();
  var tmp = new Date();
  ExpireDate.setTime(ExpireDate.getTime() + 10000);
  var curCookie = "advanced=true" + "; expires=" + ExpireDate.toGMTString() + "; path=/";
  document.cookie = curCookie;
}

function createThisCourseSeqNoCookie( value )
 {
   var ExpireDate = new Date ();
   var tmp = new Date();
   ExpireDate.setTime(ExpireDate.getTime() + 6000000);
   var curCookie = "thiscourseseqno=" + value + "; expires=" + ExpireDate.toGMTString() + "; path=/course/";
   document.cookie = curCookie;
 }


var junk = ( navigator.userAgent.indexOf('MSIE') != -1 && navigator.userAgent.indexOf('Mac') != -1 );


function clean( target )
{
   if ( junk )
   {
      target.innerHTML = '';
   }
   else
   {
      while ( target.childNodes.length > 0 )
      {
         target.removeChild(target.firstChild)
      }
   }

}

function addLoader( func )
{

    if ( eventHolder['run'] && eventHolder['run'] != null )
	{
	    var oldRun = eventHolder['run'];
	    eventHolder['run'] = function(e) { oldRun(e); func(e) }
	}
    else
	{
	    eventHolder['run'] = function(e) { func(e) }
	}

}


function search_range_redirect()
{
 var searchparams = document.mainform.searchparams.value;
 var url = "/course_search.cgi?" + searchparams + "&base=" + this.options[this.selectedIndex].value;
 document.location.href=url;
}


function getCookieData ()
{

    if ( window.ActiveXObject ) // if it's ie
    {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); // xmlhttp is global
       xmlhttp.onreadystatechange = function ()
       {
          if(xmlhttp.readyState == 4) writecookiecontent(xmlhttp.responseText);
       };
    }
    else
    {
       if (window.XMLHttpRequest) // if it's firefox etc.
       {
         xmlhttp        = new XMLHttpRequest() // xmlhttp is global
         xmlhttp.onload = function () { writecookiecontent(xmlhttp.responseText) };
       }
       else return; //
    }

	if(read_cookie( 'mys1_eid' ))
	{
	   if(document.mainform && document.mainform.cookietype)
	   {
	     var type = document.mainform.cookietype.value;
	     if(type)
	     {
	      var id = read_cookie( 'mys1_eid' )
	      var url = "http://" + document.location.hostname + "/get_cookie_data.cgi?type=" + type + "&membersid=" + id;

          xmlhttp.open("GET", url , true);
          xmlhttp.send(null);
	     }
	   }
	}

}

function writecookiecontent (content)
{
     var targ = document.getElementById('cookieText');
	 if(targ)
	 {
      document.getElementById('cookieText').innerHTML = content;
     }
}

function getElementsByClass(searchClass,node,tag)
{
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function verifyContact(f)
{
  var required_fields_names  = new Array ('name', 'email', 'message');
    var required_fields_labels = new Array ('name', 'email', 'message');
    for (var t=0; t < required_fields_names.length; ++t)
    {
        if (! f[required_fields_names[t]].value.match(/[A-Za-z0-9]/))
	{
	     alert('Please complete the ' + required_fields_labels[t] + ' field.');
	     return false;
        }
    }

	var re =/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
   if (!f.email.value.match(re))
   {
     alert('The email address you provided is not a valid email address.');
	 return false;
   }

   return true;
}

function create_remember_search_cookie(f)
{
    // var fields = new Array('level','location', 'general_subject_area', 'sub_sectors_area', 'study_mode',
	                       // 'Acount', 'Aresult', 'Alevel', 'Bcount', 'Bresult', 'Blevel', 'Ccount', 'Cresult',
						   // 'Clevel');
	// for (var i=0; i< fields.length; i++)
		// {
		  // if (f[fields[i]] && f[fields[i]].selectedIndex)
		  // {
		    // setCookie("search-" + fields[i], f[fields[i]].selectedIndex);
		  // }
		  // else
		  // {
		    // setCookie("search-" + fields[i], 0);
		  // }
		// }


    // setCookie("search-" + 'keywords', f['keywords'].value);

   return true;
}

function poplate_search_form_with_cookie()
{
  // var  fields = new Array ('level','location', 'general_subject_area', 'specific_subject_area', 'study_mode',
                           // 'Acount', 'Aresult', 'Alevel', 'Bcount', 'Bresult', 'Blevel', 'Ccount', 'Cresult',
						   // 'Clevel');

  // for (var i=0; i < fields.length; i++)
  // {
    // if (getCookie('search-' + fields[i]) && document.stepOne)
	// {
	 // if(document.stepOne[fields[i]])
	 // {
	   // document.stepOne[fields[i]].selectedIndex = getCookie('search-' + fields[i]);
     // }
	// }
  // }

  // if(document.stepOne && document.stepOne['general_subject_area'] && document.stepOne['general_subject_area'].selectedIndex > 0 )
  // {
    // prePopulateSubSectors();
  // }

  // if(document.stepOne && document.stepOne['study_mode'] && document.stepOne['study_mode'].selectedIndex > 0 )
  // {
   // showMoreOptions();
  // }

  // if (getCookie('search-keywords') && document.stepOne)
  // {
    // var kys = getCookie('search-keywords');
	// if (!kys || kys == 'undefined') { kys = ''; } else { showMoreOptions(); }
    // document.stepOne.keywords.value = kys;
  // }

}


function setCookie(sName, sValue)
{
  document.cookie = sName + "=" + escape(sValue) + "; path=/;";
}

function getCookie(sName)
{
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++)
  {
    var aCrumb = aCookie[i].split("=");
    if (sName == aCrumb[0]) return unescape(aCrumb[1]);
  }
  return 0;
}

function deleteCookie(name, path, domain)
{
  if (getCookie(name))
  {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

function run_onload_funcs()
{
  if(startRange && rangeCount)
 {
  writeRange(startRange, rangeCount);
 }
  // show this as we know the user has js since we are in this
  var targ =  document.getElementById('addmorelink');
  if(targ)
  {
    targ.style.display = 'block';
  }
  poplate_search_form_with_cookie();
}

function showHideExplorer()
{

    if ( document.getElementById('skyscraper') != null )
	{
	    if (navigator.userAgent.toLowerCase().indexOf('safari') != -1 ) { document.getElementById('skyscraper').style.display = "none"; return; }

	    if(document.body)
		{
			var iWidth = document.body.clientWidth;
		}

	    if(iWidth > 975)
		{
		    document.getElementById('skyscraper').style.display = "";
		}
	    else
		{
		    document.getElementById('skyscraper').style.display = "none";
		}

	}
}





function addmore()
{
   // lets find out whats displayed right now we defo have 3 so 4,5,6 on 7 one add_more is hidden
   var vname ='addmorelink'+(no-1);
   var no = find_first_not_displayed();
   if(no != -1)
   {
     var vname ='addmorelink'+(no+1);

     document.getElementById(no).style.display = 'inline';
	 document.getElementById(no).focus();
	 document.getElementById(vname).style.display = 'inline';
	 if(no == 2) { document.getElementById('addmorelink3').style.display = 'none'; }
   }
}


function find_first_not_displayed()
{
   for(i = 1; i < 3; i++)
   {
     var targ = document.getElementById(i);
	 if(targ.style.display == 'none')
	 {
	   return i;
	 }
   }
   return -1;
}







addLoader( run_onload_funcs );

addEvent( window, 'load', run_onload_funcs );
addEvent( window, 'resize', showHideExplorer );

