var dsMatchObj;
var matchObj;
var collectionObj;
var mapping = true;
var myMarker = new Array();

// Copyright (C) 2001 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.

// email

function checkEmail (strng) {
var error="";
if (strng == "") {
   error = "You didn't enter an email address.\n";
}

    var emailFilter=/^.+@.+\..{2,3}$/;
    if (!(emailFilter.test(strng))) { 
       error = "Please enter a valid email address.\n";
    }
    else {
//test email for illegal characters
       var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
         if (strng.match(illegalChars)) {
          error = "The email address contains illegal characters.\n";
       }
    }
return error;    
}


// phone number - strip out delimiters and check for 10 digits

function checkPhone (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a phone number.\n";
}

var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
    if (isNaN(parseInt(stripped))) {
       error = "The phone number contains illegal characters.";
  
    }
    if (!(stripped.length == 10)) {
	error = "The phone number is the wrong length. Make sure you included an area code.\n";
    } 
return error;
}


// password - between 6-8 chars, uppercase, lowercase, and numeral

function checkPassword (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a password.\n";
}

    var illegalChars = /[\W_]/; // allow only letters and numbers
    
    if ((strng.length < 6) || (strng.length > 8)) {
       error = "The password is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";
    } 
    else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
       error = "The password must contain at least one uppercase letter, one lowercase letter, and one numeral.\n";
    }  
return error;    
}    


// username - 4-10 chars, uc, lc, and underscore only.

function checkSearchTerm (strng) {
var error = "";
if (strng == "") {
   error = "You didn't enter a username.\n";
}
    var illegalChars = /[\(\)\<\>\,\;\:\\\/\"\[\]]/; // disallow these chars
    if ((strng.length < 2) || (strng.length > 40)) {
       error = "The username is the wrong length.\n";
    }
    else if (illegalChars.test(strng)) {
    error = "The username contains illegal characters.\n";
    } 
return error;
}       


// non-empty textbox

function isEmpty(strng) {
var error = "";
  if (strng.length == 0) {
     error = "The mandatory text area has not been filled in.\n"
  }
return error;	  
}

// was textbox altered

function isDifferent(strng) {
var error = ""; 
  if (strng != "Can\'t touch this!") {
     error = "You altered the inviolate text area.\n";
  }
return error;
}

// exactly one radio button is chosen

function checkRadio(checkvalue) {
var error = "";
   if (!(checkvalue)) {
       error = "Please check a radio button.\n";
    }
return error;
}

// valid selector from dropdown list

function checkDropdown(choice) {
var error = "";
    if (choice == 0) {
    error = "You didn't choose an option from the drop-down list.\n";
    }    
return error;
}    


function chkTypes(x) {
   var Ary;
   Ary = ['gisbox','wmsbox','projectbox','databasebox','documentbox','orgbox','otherbox'];
   for (var i = 0; i < Ary.length; i++) {
      if (document.getElementById(Ary[i])) { document.getElementById(Ary[i]).checked = x }
   }
}

function chkCats(x) {
   var Ary;
   Ary = ['biotaBox','agBox','physBox','builtBox'];
   for (var i = 0; i < Ary.length; i++) {
      document.getElementById(Ary[i]).checked = x
   }
}

function setOrgFilter(l) {
	orgname = l;
 	document.getElementById('orgNameMatchDiv').innerHTML = '';
	changeObjectVisibility('orgNameMatchDiv','hidden');
        document.getElementById("orgname").value = l;
	ceicQuery();
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  

  if(!d) d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; 
    n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); 
  return x;
}

function getStyleObject(objectId) {
  // checkW3C DOM, then MSIE 4, then NN 4.
  //
  if(document.getElementById && document.getElementById(objectId)) {
return document.getElementById(objectId).style;
   }
   else if (document.all && document.all(objectId)) {  
return document.all(objectId).style;
   } 
   else if (document.layers && document.layers[objectId]) { 
return document.layers[objectId];
   } else {
return false;
   }
}

	function listTypes()
	{
	    var rt = '';	

	     if (document.getElementById('projectbox').checked == true) {
		if (rt.length > 1) { rt = rt + ',' }
             	rt = rt + 'project';
		}
	     if (document.getElementById('gisbox').checked == true) {
		if (rt.length > 1) { rt = rt + ',' }
             	rt = rt + 'gis,wms';
		}
	     if (document.getElementById('otherbox').checked == true) {
		if (rt.length > 1) { rt = rt + ',' }
             	rt = rt + 'other,database,document,org';
		}

	   return rt;
	}

	function listTopics()
	{
	   var rt = '';	
           var Ary;
   	   Ary = ['biotaBox','agBox','physBox','builtBox'];
           for (var i = 0; i < Ary.length; i++) {
	     if (document.getElementById(Ary[i])) {
	     if (document.getElementById(Ary[i]).checked == true) {
		if (rt.length > 1) { rt = rt + ',' }
             	rt = rt + document.getElementById(Ary[i]).value;
		}
	     }
	   }
	   return rt;
	}

        function OBJ_show(src,id,targetDiv)
        {
          document.getElementById(targetDiv).innerHTML = '';
	  var Url = '';
          __AjaxProcessFunction = __objInfoFill;
          changeObjectVisibility("objInfoFrame","visible");
          document.getElementById(targetDiv).innerHTML = '<p><img src="/ceic/images/loading.gif">';
	  Url = "/plugins/datasets/assets/gwt/MDmin.html?src=" + src + "&id=" + id;
//alert(Url);
            __AjaxGet(Url);
        }


function ceicQuery(type,name)
{
   var term = '';
   var org = '';
   var node = '';
   var phrase = '';
   var types = '';
   var topics = '';
   var topicArray = [];
   var typeArray = [];
   var Url = '';
   var qStr = '';

   if (!(checkSearchTerm(document.getElementById('term').value))) {   
     term = document.getElementById('term').value; 
   }


   if (document.getElementById('orgname')) { org = document.getElementById('orgname').value; }
   if (document.getElementById('node')) { node = document.getElementById('node').value; }
   if (document.getElementById('phrase')) { phrase = document.getElementById('phrase').checked; }
   types = listTypes();
   topics = listTopics();
   topicArray = topics.split(",");   
   typeArray = types.split(",");

   Url = "/plugins/datasets/assets/php/ceicQuerySpatial.php?";
   qStr = ''; 

   if (mapping) {
     if (map_type == 'ol') {
      qStr = qStr + 'bbox=' + bbox + '&srid=2&'
     }
     else {
      qStr = qStr + 'ext=' + ext + '&'
     }
   }

//alert(ext);
   if ((typeArray.length > 0) && (typeArray.length < 8)) {qStr = qStr + 'cat=' + escape(types) + '&'}
   if ((topicArray.length > 0) && (topicArray.length < 8)) {qStr = qStr + 'topic=' + escape(topics) + '&'}
   if (term.length > 0) {qStr = qStr + 'term=' + escape(term) + '&'}
   if (phrase) {qStr = qStr + 'phrase=1' + '&'}
   if (org.length > 0) {qStr = qStr + 'org=' + escape(org) + '&'}
   if (node.length > 0) {qStr = qStr + 'node=' + escape(node) + '&'}

   if (mapping) {
   	gmap.clearOverlays();
	}

//alert(qStr);
//   ceicDataTable.deleteRows(0,100);
   if (ceicDataTable) {
   	ceicDataTable.showTableMessage(YAHOO.widget.DataTable.MSG_LOADING, YAHOO.widget.DataTable.CLASS_LOADING);
   	ceicDataSource.sendRequest(qStr,
       		ceicDataTable.onDataReturnInitializeTable, ceicDataTable);
	}
   else {
        __AjaxProcessFunction = __ajaxObjFill;
//        changeObjectVisibility("json","visible");
        document.getElementById('json').innerHTML = '<p><img src="images/loading.gif">';

       __AjaxGet(Url + qStr)
	}
}

function listQuery(type,cat)
{
   var Url = '';
   var qStr = '';

   if (type == 'gforge') {
      Url = "/plugins/datasets/assets/php/list.php?limit=1000&src=ds&group_id=" + cat;
   }
   else {
      Url = "/plugins/datasets/assets/php/list.php?limit=1000&src=" + type + "&cat=" + cat;
   }

   qStr = ''; 
//alert(qStr);
        __AjaxProcessFunction = __ajaxObjFill;
//        changeObjectVisibility("json","visible");
        document.getElementById('json').innerHTML = '<p><img src="/plugins/datasets/images/loading.gif">';

       __AjaxGet(Url + qStr)
}

function collectionQuery(collection)
{
   var Url = '';
   var qStr = '';

   Url = "assets/php/collection.php";
   qStr = '?collection=' + collection; 
//alert(qStr);
        __AjaxProcessFunction = __ajaxCollectionFill;
//        changeObjectVisibility("json","visible");
        document.getElementById('json').innerHTML = '<p><img src="/plugins/datasets/images/loading.gif">';

       __AjaxGet(Url + qStr)
}


function __ajaxObjFill(AxlResponse)
{
//  alert(AxlResponse);
    var obj = {};

    try { obj = eval( '(' + AxlResponse + ')' ) }
    catch (e) { return true }

    document.getElementById('jsonHeader').innerHTML = obj.ResultSet.Filter;

    if (obj.ResultSet.ResultType == 'cat') {
	matchObj = obj;
	listMatchObj('json','cat')
	}
    else {
	dsMatchObj = obj;
    	listDsMatchObj('json')
	}

    return true;
}

function __ajaxCollectionFill(AxlResponse)
{
//  alert(AxlResponse);
    var obj = {};

    try { collectionObj = eval( '(' + AxlResponse + ')' ) }
    catch (e) { return true }

    document.getElementById('jsonHeader').innerHTML = 'CEIC Special Collection';

    listCollection('json');
    return true;
}

function postComment()
{
   var email = document.getElementById('cmtEmail').value; 
//   var asArray = document.getElementById('cmtasArray').value; 
   var comment = document.getElementById('cmtComment').value; 

   var Url = "api/ceicCommentPost.php?email=" + email + "&cmt=" + comment;
   alert(Url)
}

function listDsMatchObj(targetDiv)
         {
             var Html;
             var line;
             var list;
             var str;
             var icon;

             try {
                str = dsMatchObj.ResultSet.Result
             }
             catch (err){
               document.getElementById(targetDiv).innerHTML = '';
               return
             }
             document.getElementById(targetDiv).innerHTML = '';
             fill = '';
             Html = '';
             list = eval('dsMatchObj.ResultSet.Result');
             where = eval('dsMatchObj.ResultSet.Where');
             var len = list.length;
             for (var n = 0; n < len; n++) {
                 if (list[n].cat == 'project') {
                        icon = "/plugins/datasets/images/file-make.png";
                 }
                 else if (list[n].cat == 'document') {
                        icon = "/plugins/datasets/images/docs.gif";
                 }
                 else if (list[n].cat.indexOf('gis') == 0) {
                        icon = "/plugins/datasets/images/file-vectorgfx.png";
                 }
                 else if (list[n].cat.indexOf('vector') > -1) {
                        icon = "/plugins/datasets/images/file-vectorgfx.png";
                 }
                 else if (list[n].cat.indexOf('raster') > -1) {
                        icon = "/plugins/datasets/images/file-vectorgfx.png";
                 }
                 else if (list[n].cat.indexOf('spatial') > -1) {
                        icon = "/plugins/datasets/images/file-vectorgfx.png";
                 }
                 else if (list[n].cat == 'web') {
                        icon = "/plugins/datasets/images/file-html.png";
                 }
                 else if (list[n].cat == 'database') {
                        icon = "/plugins/datasets/images/file-cdtrack.png";
                 }
                 else if (list[n].cat.indexOf('computer') > -1) {
                        icon = "/plugins/datasets/images/file-cdtrack.png";
                 }
                 else if (list[n].cat == 'org') {
                        icon = "/plugins/datasets/images/group.gif";
                 }
                 else if (list[n].cat == 'place') {
                        icon = "/plugins/datasets/images/world.png";
                 }
                 else  {
                        icon = "/plugins/datasets/images/file-unknown.png";
                 }

		var infoReq;
		var hgt = 420;
		infoReq = '/plugins/datasets/assets/gwt/MDmin.html?id=' + list[n].id;
//infoReq = '';
		if (activeKeys) {
			infoReq = infoReq + '&amp;active=1';
			hgt += 50;
		}
		infoReq = infoReq + '&amp;width=520&amp;height=' + parseInt(hgt); 
	
		var label = list[n].label;
		label = label.replace(/[\(\)']/g, "") // removes "(", ")"	
		
		//label 
		// create the link line
		if (gmap) {

try {
	 	  	 line = '<img src="' + icon + '">&nbsp;<a href="#" onmouseover="showMarker(\'' + list[n].lat + '\',\'' + list[n].lon + '\',\'\');" onClick="tb_show(\'' + label + '\',\'' + infoReq + '\');">' + label + ' (' + list[n].cat + ')</a><br>';
}
catch (e) { alert(line) }

		}
	        else {
                 line = '<img src="' + icon + '">&nbsp;<a href="#" onClick="tb_show(\'' + label + '\',\'' + infoReq + '\')">' + label + ' (' + list[n].cat +  ')</a><br>';
		}

                Html = Html + line;
             }

            if (Html == '') {
               document.getElementById(targetDiv).innerHTML = 'No matching datasets';
                }
            else {
               document.getElementById(targetDiv).innerHTML = Html;
                }

         }

function listCollection(targetDiv)
         {
             var Html;
             var line;
             var list;
             var str;
             var icon;

             try {
                str = collectionObj
             }
             catch (err){
               document.getElementById(targetDiv).innerHTML = '';
               return
             }
             document.getElementById(targetDiv).innerHTML = '';
             fill = '';
             Html = '';
	     
             list = eval('collectionObj["Administrative Divisions"]');
             var len = list.length;
             for (var n = 0; n < len; n++) {
		var infoReq;
		var hgt = 420;
		infoReq = '/plugins/datasets/assets/gwt/MDmin.html?id=' + list[n].id;

		if (activeKeys) {
			infoReq = infoReq + '&amp;active=1';
			hgt += 50;
		}
		infoReq = infoReq + '&amp;width=520&amp;height=' + parseInt(hgt); 
	
		var label = list[n].label;
		label = label.replace(/[\(\)']/g, "") // removes "(", ")"	
		
		//label 
		// create the link line

                 line = '<img src="' + icon + '">&nbsp;<a href="#" onClick="tb_show(\'' + label + '\',\'' + infoReq + '\')">' + label + '</a><br>';

                Html = Html + line;
             }

            if (Html == '') {
               document.getElementById(targetDiv).innerHTML = 'No matching datasets';
                }
            else {
               document.getElementById(targetDiv).innerHTML = Html;
                }

         }

function listMatchObj(targetDiv,type)
         {
             var Html;
             var line;
             var list;
             var str;
             var icon;

             try {
                str = matchObj.ResultSet.Result
             }
             catch (err){
               document.getElementById(targetDiv).innerHTML = '';
               return
             }
             document.getElementById(targetDiv).innerHTML = '';
             fill = '';
             Html = '';
             list = eval('matchObj.ResultSet.Result');
             var len = list.length;
             icon = "/plugins/datasets/images/book-open.png";
             for (var n = 0; n < len; n++) {
		if (type == 'cat') {
                 line = '<img src="' + icon + '">&nbsp;<a href="#" onCLick="listQuery(\'ds\',\'' + list[n].shortname + '\')">' + list[n].label + '</a><br>';
		}
		else {	
                 line = '<img src="' + icon + '">&nbsp;<a href="#" onClick="tb_show(\'' + escape(list[n].label) + '\',\'assets/gwt/MDmin.html?id=' + list[n].id  + '&amp;width=420&amp;height=400\')">' + list[n].label + '</a><br>';
		}
                Html = Html + line;
             }

            if (Html == '') {
               document.getElementById(targetDiv).innerHTML = 'No matches found';
                }
            else {
               document.getElementById(targetDiv).innerHTML = Html;
                }

         }
 
