// thanks http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD
function areArraysEqual(array1, array2) {
   var temp = new Array();
   if ( (!array1[0]) || (!array2[0]) ) { // If either is not an array
      return false;
   }
   if (array1.length != array2.length) {
      return false;
   }
   // Put all the elements from array1 into a "tagged" array
   for (var i=0; i<array1.length; i++) {
      var key = (typeof array1[i]) + "~" + array1[i];
   // Use "typeof" so a number 1 isn't equal to a string "1".
      if (temp[key]) { temp[key]++; } else { temp[key] = 1; }
   // temp[key] = # of occurrences of the value (so an element could appear multiple times)
   }
   // Go through array2 - if same tag missing in "tagged" array, not equal
   for (var i=0; i<array2.length; i++) {
      key = (typeof array2[i]) + "~" + array2[i];
      if (temp[key]) {
         if (temp[key] == 0) { return false; } else { temp[key]--; }
      // Subtract to keep track of # of appearances in array2
      } else { // Key didn't appear in array1, arrays are not equal.
         return false;
      }
   }
   // If we get to this point, then every generated key in array1 showed up the exact same
   // number of times in array2, so the arrays are equal.
   return true;
}


// type is like xml or csv
function linkToData(type) {
	var hash = window.location.hash;
	var hash_arr 	= hash.split(url_delimiter);
	found=false;
	for (var i=0;i<hash_arr.length;i++) {
		if (hash_arr[i].search('view') > -1) {
			hash_arr[i] = "view=" + type; 
			var found = true;
			break;
		}
	}	
	if (!found) { hash_arr[hash_arr.length] = "view=" + type; }
	var new_hash = hash_arr.join(url_delimiter);
	if (!new_hash) new_hash = hash;
	return 'http://' + dev_url + 'rest/?' + stripLeadingHash(new_hash);
}	

// associative arrays in our RESTy urls are like this:  units/note/=value
// we want to convert that to brackets before ajax call:  units[note]=value
// this func returns url string with defined array params converted
function convertArraysInUrl(url_str) {
	var array_params = ['units','string_selects']; 	// define params in the url that are in need of brackets to replace %
	var url_arr = url_str.split('&'); // the url string as an arr
	for (var i=0;i<array_params.length;i++) {
		var convert_param = array_params[i];
		for (var j=0;j<url_arr.length;j++) {
			var input = url_arr[j];
			var input_split = input.split("=");  
			var param = input_split[0];
			var value = input_split[1];
			if (input_split[0].search(convert_param) > -1) {
				// this is one of the params we are looking for
				var param_arr = input.split('/');
				var new_param = param_arr[0] + '[' + param_arr[1] + ']';
				url_arr[j] = new_param + '=' + value;
			}
		}	
	}
	return url_arr.join('&');
}




function getResultsInfo() {
	$('bookmark_text').innerHTML = '\<div style = "text-align:center;">Inspecting your result set<br>' + loading() + '\</div>';
	Element.show('bookmark_container');
	Element.show('bookmark_text');
	var dir = "http://" + dev_url; 
    new Ajax.Updater(
		'bookmark_text',
		dir + "app/scripts/results_info.php",
			{
				 method: "GET",
				 onComplete: function() {  }
			} 
	)	
}


// valid pages are set in bookmark.php
// : $valid_pages = array('homepage','results');
function createBookmark(page) {
	$('bookmark_text').innerHTML = '\<div style = "text-align:center;">Creating permanent link, please wait.\<br>' + loading() + '\</div>';
	Element.show('bookmark_container');
	Element.show('bookmark_text');
	// we are going to add to the url if this is the homepage
	var add_to = '';
	if (page == 'homepage') {
		// server may not have default_div or open_widgets because these things
		// can be changed without notifying the server..
		var open_widgets_str = open_widgets.join(',');
		add_to    =  "&open_widgets=" + open_widgets_str;
		add_to 	+=  "&default_div=" + default_div;
		// if this is the homepage we should not refer to bookmark.php in it's full url
		// this is for making easy to create the cached_homepage..
		var	dir = '';
	}
	else 	{
		// the calling page is not the homepage, use the full url to find bookmark.php
		dir = 'http://' + dev_url;
	}
		new Ajax.Updater(
			"dummy", 
			dir + "bookmark.php?page=" + page + add_to,
			{
			 method: "GET",
			 onComplete: function() {
	
					 if ($('dummy').innerHTML) {
						 	$('bookmark_text').innerHTML = $('dummy').innerHTML; 
					 }
					 else
					 {
						 // no
			 			 //bookmark returned nothing, error message 
						 $('bookmark_text').innerHTML = "Sorry, \<br> we are experiencing a technical problem\<br>and cannot set trackbacks at this time,\<br> please try again later.";
					 }
			 	}
			}
		);
}





function cartUpdate(ring_obs_id,action,file_name) {
  $('cart_status').innerHTML = loading() + " please wait.."; 
  var add_to_url = '';
  if (file_name) add_to_url = '&file_name='+file_name;
  // fill in the defaul div
  if (typeof(ring_obs_id)=='string') {
	  var ring_obs_ids = ring_obs_id;
  } else var ring_obs_ids = ring_obs_id.join(',');
  if (action != 'add' || action != 'remove') {
	  // this is not a simple add/remove, send the hash along with.. 
	  add_to_url +=  '&' + stripLeadingHash(window.location.hash);
  }
  
	add_to_url = convertArraysInUrl(add_to_url);

	new Ajax.Request(
		"http://" + dev_url + "app/scripts/cart/cart.php?id=" + ring_obs_ids + '&do=' + action + add_to_url, 
		{ method: "get",
		  onSuccess: function(transport,json) {
			  if (json.cart_no) cart_no = json.cart_no;
			  updateHash(); // adding the cart_no to the hash
			  
			  if ($('cart_count')) $('cart_count').innerHTML = json.cart_count; 
			  
			  if (!json.cart_count) { 
				 $('cart_status').innerHTML = "cart is empty";
			  } else {
				 $('cart_status').innerHTML = json.cart_count + " items in cart";
				 cart_count = json.cart_count;
			  }
			  
			 if (view=='cart') {
				 load2();
				 getCartDisplay();
			}}});			
}



function textInputMonitor(field,ms) {
	var field_monitor = new Array();
	// which field are we working on? defines which global monitor we use
	switch(field) {
		case 'page':
				field_monitor = page_monitor;
				break;
		case 'page_cart':
				field_monitor = page_cart_monitor;
				break;
		default:
				field_monitor = text_field_monitor;
	}
		var value = $F(field);
		if (timer) clearTimeout(timer);
		timer = setTimeout(
			function timedUpdate() {
				if (field_monitor[field_monitor.length-1]  == value){
					// the user has not moved in 2 seconds
					setTimeout("updateHash()",0);
					// tidy up, keep the array small..
					if (field_monitor.length > 3) field_monitor.shift();
				} else {
					// array is changing, user is still typing
					// maintain our array with our new value
					field_monitor[field_monitor.length]  = value;
					textInputMonitor(field);
				}
		}
		,ms);
	// update the global monitor 
	switch(field) {
		case 'page':
				page_monitor = field_monitor;
				break;
		case 'page_cart':
				page_cart_monitor = field_monitor;
				break;
		default:
				text_field_monitor = field_monitor;
	}
}

	
function stripLeadingHash(string) {
	if (!string) return;
	if (string.substring(0,1) == '#')  {
			// trim that hash char 
			return string.substring(1);
	} else return string;	
}


function in_array(obj,array) {
	for (var i=0;i<array.length;i++) {
		if (array[i] == obj) return true;
	}
	return false;
}
function clearAll(post_names) {
	var all = Form.serialize($('form1'));
}
function display_result(val) {
	var repr;
	repr  = "";
	repr += "Type: " + typeof val + "\n";
	repr += "Value: ";
	if (typeof val == "object" ||
		typeof val == "array") {
		repr += "{ ";
		for (var i in val) 
			repr += i + ": " + val[i] + ", ";
		repr = repr.substr(0, repr.length-2) + " }";
	} else {
		repr += val;
	}
	alert(repr);
}
// this function loads an event on page load
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}
//  This JavaScript allows IE to change the background of the labels 
// just like modern browsers do with the :hover pseudoclass:
function initChecklist() {
    if (document.all && document.getElementById) {
        // Get all unordered lists
	   var lists = document.getElementsByTagName("ul");
        
        for (i = 0; i < lists.length; i++) {
            var theList = lists[i];
            
		  // Only work with those having the class "checklist"
            if (theList.className.indexOf("checklist") > -1) {
                var labels = theList.getElementsByTagName("label");
                
			 // Assign event handlers to labels within
                for (var j = 0; j < labels.length; j++) {
                    var theLabel = labels[j];
                    theLabel.onmouseover = function() { this.className += " hover"; };
                    theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
                }
            }
        }
    }                         
}
addLoadEvent(initChecklist);
addLoadEvent(function() {
  /* more code to run on page load */ 
});
function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
function unHighlightButton(div) {
		$(div).style.color = "gray";
}
function highlightButton(div) {
		$(div).style.color = "red";
}
