/*Array
(
    [libs] => Array
        (
            [0] => behaviour
            [1] => default
            [2] => kwlib
        )

    [apps] => Array
        (
            [product] => product
            [category] => category
            [brand] => brand
            [cart summary] => cart summary
            [cart] => cart
            [brand_store] => brand_store
            [dept_nav] => dept_nav
            [breadcrumbs] => breadcrumbs
            [meal_category_nav] => meal_category_nav
        )

    [theme] => default
    [media] => screen
)
*//*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   Description:
   	
   	Uses css selectors to apply javascript behaviours to enable
   	unobtrusive javascript in html documents.
   	
   Usage:   
   
	var myrules = {
		'b.someclass' : function(element){
			element.onclick = function(){
				alert(this.innerHTML);
			}
		},
		'#someid u' : function(element){
			element.onmouseover = function(){
				this.innerHTML = "BLAH!";
			}
		}
	};
	
	Behaviour.register(myrules);
	
	// Call Behaviour.apply() to re-apply the rules (if you
	// update the dom, etc).

   License:
   
   	This file is entirely BSD licensed.
   	
   More information:
   	
   	http://ripcord.co.nz/behaviour/
   
*/   

var Behaviour = {
	list : new Array,
	
	register : function(sheet){
		Behaviour.list.push(sheet);
	},
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},
	
	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);
				
				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},
	
	addLoadEvent : function(func){
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

/*
   The following code is Copyright (C) Simon Willison 2004.

   document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names, 
     class names and ids and can be nested. For example:
     
       elements = document.getElementsBySelect('div#main p a.external')
     
     Will return an array of all 'a' elements with 'external' in their 
     class attribute that are contained inside 'p' elements that are 
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);					// make sure element exists - krw 10/18/2007
      if (element && tagName && (element.nodeName.toLowerCase() != tagName)) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
	    if (currentContext[h]) {						// make sure 'currentContext[h]' exists - krw 10/18/07
		    elements = currentContext[h].getElementsByTagName(tagName);
		}
        }
	if (elements) {								// make sure 'elements' exists - krw 10/18/07
		for (var j = 0; j < elements.length; j++) {
		  found[foundCount++] = elements[j];
	}
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
	    if (currentContext[h]) {						// make sure 'currentContext[h]' exists - krw 10/18/07
		    elements = currentContext[h].getElementsByTagName(tagName);
	    }
        }
	if (elements) {
		   for (var j = 0; j < elements.length; j++) {
		  found[foundCount++] = elements[j];
		}
	}
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/

$$ = function(selector){return document.getElementsBySelector(selector);}
$ = function(id) { return document.getElementById(id); }

ajax_server = "http://whittakermountaineering.com/index.php?";

kajax = function(url, method, vars, callback)
{
	var xmlhttp;

	url += "&ajax=1";							// FIXME !!! 
	try { 
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); 			// MS IE is most prolific browser, we try it 1st
	} catch (e) { 
		try { 		
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 	// ditto
		} catch (e) { 
			try { 
				xmlhttp = new XMLHttpRequest(); 		// everybody not MS
			} catch (e) { 
				xmlhttp = false; 
			}
		}
	}

	if (xmlhttp) {
		xmlhttp.onreadystatechange = function(o) {
			if ( (xmlhttp.readyState == 4)  ) {
				callback(xmlhttp);
			}
		}
		method = method.toUpperCase();
		if ( method == "POST" ) {
			xmlhttp.open(method, url, true);
			xmlhttp.setRequestHeader("Method", "POST "+ url +" HTTP/1.1");
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xmlhttp.send(vars);					// Send name = value pairs or 
		} else {							// Not POST, assume GET
			xmlhttp.open(method, url + "?"+ vars, true);		// add vars to GET url
			xmlhttp.send(null);					// Send name = value pairs or 
		}
	}

	return xmlhttp;
}

var remove_node = function(id)
{
	var o = $(id);
	if (o) {
		o.parentNode.removeChild(o);
	}
}


var kwajaxGenericCallback = function (oXML) {
	var kajaxDebug = 0;
	if ( kajaxDebug==1 ) {
		alert(oXML.responseText);
	}
	eval(oXML.responseText);

	if (std_behaviours) {
		Behaviour.apply(std_behaviours);
	}
}


doit = function(frm)
{
	values = getFormValues(frm);
	kajax("mypage.php?id=contents&func=foo&args[]=disco&args[]=like&args[]=Kenny", "POST", values, myCallback);
	return false;
}

getFormValues = function(frm)
{
	var objForm;
	if (typeof(frm) == "string")
	objForm = $(frm);
	else
	objForm = frm;
	var sXml = "";
	if (objForm && objForm.tagName == 'FORM') {
		var formElements = objForm.elements;
		for( var i=0; i < formElements.length; i++) {
			if ((formElements[i].type == 'radio' || formElements[i].type == 'checkbox') && formElements[i].checked == false) {
				continue;
			}
			var name = formElements[i].name;
			if (name) {
				sXml += escape(name)+"="+escape(formElements[i].value);
				sXml += "&";
			} 
		}
	}

	return sXml;
}

var trip_planner = new function() 
{
	this.callback = function()
	{
		var o = this.img;
		o.src = "http://whittakermountaineering.com//media/images/button_tripPlannerAdded.gif";
		o.added = 1;
//		o.width = "154";
//		o.height = "21";
	}
	this.add = function(o) {
		this.img = o;

		if (o.added) {
			return false;
		}
		o.src = "http://whittakermountaineering.com//media/images/loading_spinner.gif";
//		o.height = "16";
//		o.width = "16";
		var rel = o.getAttribute('rel');
		var url = "http://whittakermountaineering.com/index.php?"
			+ "&gigmod=ajax"
			+ "&appnam=trip_planner"
			+ "&appact=add"
			+ "&item="+rel
			+ "&appcb=trip_planner.callback()"
		;
		kajax(url, "GET", "", kwajaxGenericCallback);

		alert('hi from add()');
		return true;
		//alert(o.src +", "+rel);
	}
}
var std_behaviours = {
	'input.string' : function(el) {
		var size=parseInt(el.size);
		if (size > 0) {
			el.style.width = size + "em";
		}
	},
	'a[target=_blank]' : function(el) {
		el.onclick = function() {
			var url = this.href;
			var caption = this.innerHTML;
			GB_showFullScreen(caption, url);
			return false;
		}
	},
	/*
	'img.add2tp' : function(el) {
		el.onclick = function() {
			trip_planner.add(this);
			return false;
		}
	},
	'a.add2tp img' : function(el) {
		el.onclick = function() {
			trip_planner.add(this);
			return false;
		}
	},
	/**/
	'a.show_trip_planner_summary' : function(el) {
		el.onclick = function() {
			var url = "http://whittakermountaineering.com/index.php?"
				+ "&gigmod=ajax"
				+ "&appnam=trip_planner"
				+ "&appact=sizeof"
				+ "&apptid=trip_planner_sizeof"
			;
			kajax(url, "GET", "", kwajaxGenericCallback);
			return false;
		}
	}
}

Behaviour.register(std_behaviours);

var std_table_a_view_details = function(app_name, el)
{
	var cb_func = app_name + "_entry_form_callback()";
	var url = el.getAttribute('href')
		+ "&gigmod=ajax"
		+ "&apptid=app_" + app_name
		+ "&appcb="+ cb_func
	;
	kajax( url, "GET", "", kwajaxGenericCallback);

	return false;
}

function pop1(url) 
{
 var width  = 900;
 var height = 700;
 var left   = (screen.width  - width)/2;
 var top    = (screen.height - height)/2;
 var params = 'width='+width+', height='+height;
 params += ', top='+top+', left='+left;
 params += ', directories=no';
 params += ', location=no';
 params += ', menubar=no';
 params += ', resizable=yes';
 params += ', scrollbars=yes';
 params += ', status=no';
 params += ', toolbar=no';
 newwin=window.open(url,'onepopup', params);
 if (window.focus) {newwin.focus()}
 return false;
}


function grayOut(vis, options) {
  // Pass true to gray out screen, false to ungray
  // options are optional.  This is a JSON object with the following (optional) properties
  // opacity:0-100         // Lower number = less grayout higher = more of a blackout 
  // zindex: #             // HTML elements with a higher zindex appear on top of the gray out
  // bgcolor: (#xxxxxx)    // Standard RGB Hex color code
  // grayOut(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
  // Because options is JSON opacity/zindex/bgcolor are all optional and can appear
  // in any order.  Pass only the properties you need to set.
  var options = options || {}; 
  var zindex = options.zindex || 50;
  var opacity = options.opacity || 70;
  var opaque = (opacity / 100);
  var bgcolor = options.bgcolor || '#000000';
  var dark=document.getElementById('darkenScreenObject');
  if (!dark) {
    // The dark layer doesn't exist, it's never been created.  So we'll
    // create it here and apply some basic styles.
    // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
    var tbody = document.getElementsByTagName("body")[0];
    var tnode = document.createElement('div');           // Create the layer.
        tnode.style.position='absolute';                 // Position absolutely
        tnode.style.top='0px';                           // In the top
        tnode.style.left='0px';                          // Left corner of the page
        tnode.style.overflow='hidden';                   // Try to avoid making scroll bars            
        tnode.style.display='none';                      // Start out Hidden
        tnode.id='darkenScreenObject';                   // Name it so we can find it later
    tbody.appendChild(tnode);                            // Add it to the web page
    dark=document.getElementById('darkenScreenObject');  // Get the object.
  }
  if (vis) {
    // Calculate the page width and height 
    if( document.body && ( document.body.scrollWidth || document.body.scrollHeight ) ) {
        var pageWidth = document.body.scrollWidth+'px';
        var pageHeight = document.body.scrollHeight+'px';
    } else if( document.body.offsetWidth ) {
      var pageWidth = document.body.offsetWidth+'px';
      var pageHeight = document.body.offsetHeight+'px';
    } else {
       var pageWidth='100%';
       var pageHeight='100%';
    }   
    //set the shader to cover the entire page and make it visible.
    dark.style.opacity=opaque;                      
    dark.style.MozOpacity=opaque;                   
    dark.style.filter='alpha(opacity='+opacity+')'; 
    dark.style.zIndex=zindex;        
    dark.style.backgroundColor=bgcolor;  
    dark.style.width="100%"; // pageWidth;
    dark.style.height= pageHeight;
    dark.style.display='block';                          
  } else {
     dark.style.display='none';
  }
}

kwgopop = new function()
{
	this.id = "";
	this.close = function() {
		document.body.style.overflow = "auto";
		var o = $(this.id);
		o.style.display = 'none';
		grayOut(false);
		window.onresize = this.saved_resize_func;
	};
	this.setup_canvas = function()
	{
		var o = document.getElementById(kwgopop.id);
		var st = document.body.scrollTop;
		document.body.style.overflow = "hidden";
		window.scrollTo(0,st)
		var w, h, t, l;
		w = window.innerWidth;
		h = window.innerHeight;
		t = Math.round(h * .1);
		l = Math.round(w * .1);
		h = Math.round(h * .8);
		w = Math.round(w * .8);
		o.style.left = l + "px";
		o.style.top = st + t + "px";
		o.style.width = w + "px";
		o.style.height = h + "px";
		o.style.display = "block";
		o.style.overflow = "auto";
		o.style.zIndex = 1001;
	}
	this.open = function(id) {
		grayOut(true);
		this.id = id;
		this.move_node_directly_under_body(id);
		this.setup_canvas();
		this.saved_resize_func = window.onresize;
		window.onresize = function() {
			kwgopop.setup_canvas();				// call our resize func
			if (kwgopop.saved_resize_func) {
				kwgopop.saved_resize_func();			// call the orig. resize function
			}
		}
	}
	this.move_node_directly_under_body = function(id) {
		var tbody = document.getElementsByTagName('body')[0];
		var node_to_move = $(id);
		var rv = false;
		if (node_to_move && (node_to_move.parentNode.tagName != 'BODY')) {
			var orphan = node_to_move.parentNode.removeChild( node_to_move );
			this.add_close_button(orphan);
			rv = tbody.appendChild( orphan );	
		}

		return rv;
	}
 	this.add_close_button = function(el) {
		var tnode = document.createElement('a');           // Create the layer.
		//tnode.textContent = "close";
		tnode.href = "javascript:kwgopop.close();";
		tnode.className = "kwgopop_close_button";
		var new_node = el.appendChild(tnode);                            // Add it to the web page
	}
}
var order_complete = function (order_num)
{
	var url = "http://whittakermountaineering.com/index.php" + "?"
		+ "&gigmod=ajax"
		+ "&appnam=checkout"
		+ "&appact=notify"
		+ "&on="+order_num
	;
	kajax( url, "GET", "", kwajaxGenericCallback);

	return false;
}

var local_behaviours = {
	'a' : function(el) {
		var href = el.href;
		if (href.substr(-5)=='#beta') {
			el.onclick = function () {
				alert("This feature has not yet been implemented - Beta Test Site");
				return false;
			}
		}
	}
}
Behaviour.register(local_behaviours);

//var GB_ROOT_DIR = "http://mydomain.com/greybox/";

/* script app: ../product/screen.js */
var product_tab = new function()
{
	this.current = "tab_details";
	this.open = function(id) {
		if (this.current != id) {
			$(this.current).parentNode.parentNode.className = 'tab';
			$(this.current + "_canvas").className = 'tab';

			$(id).parentNode.parentNode.className = 'tab_selected';
			$(id + "_canvas").className = 'tab_selected';
			this.current = id;
		}
	}
}

var product_entry_form_callback = function()
{
	Behaviour.apply(product_entry);						// re-apply beahaviour rules because we reloaded div with add_todo formn
}

var product_entry = {
	'a.swatch' : function(el) {
		el.onclick = function() {
			var base_url = el.getAttribute('media');
			var normal_img = $$('li.photo_normal img')[0];

			normal_img.id = "product_photo_normal";

			normal_img.src = base_url + "/normal.jpg";
			$('zoom').rel = base_url + "/zoomed.jpg";

			return false;
		}
	},
	'ul.tabs_nav li h2 a' : function (el) {
		el.onclick = function() {
			product_tab.open( this.id );
		}
	},
	/*
	'div#tab_sizing_canvas table.wtable thead' : function(el) {
		//el.innerHTML = "<tr><th align='left'>Item</th><th align='left'>Description</th></tr>";
	},
/**/
	'div#tab_specs_canvas table.wtable thead' : function(el) {
		//el.innerHTML = "<tr><th align='left'>Specification</th><th align='left'>Description</th></tr>";
	}
};
Behaviour.register(product_entry);

var jump_to_anchor = function(aname)
{
	window.location.hash = aname;
}

var media_activate_pdf = function(ndx)
{
}

var media_activate_image = function(ndx)
{
}

var media_activate_audio = function(ndx)
{
}

var media_activate_video = function(ndx)
{
}

var last_media_hover = 0;
var media_hover = function(ndx)
{
	if(last_media_hover) {
		last_media_hover.style.display = 'none';
	}
	var o = $('media_caption_'+ndx);
	o.style.display = 'block';
	last_media_hover = o;
}
/* script app: ../category/screen.js */
/* script app: ../brand/screen.js */
/* script app: ../cart summary/screen.js */
/* script app: ../cart/screen.js */
var remove_from_cart = function(id)
{
	var obj = document.getElementById('cart_qty_'+id);
	if (obj) {
		obj.value = 0;
		var cart_obj = document.getElementById('cart_form');
		if (typeof cart_obj == "object") {
			cart_obj.submit();
		}
	}

	return false;
}
/* script app: ../brand_store/screen.js */
var bjs_brand_store = {
        'form#shop_brand_store_select select' : function(el) {
                el.onchange = function() {
			var id = this.value;
			this.parentNode.action += '&id=' + id;
			this.parentNode.submit();
			return false;
		}
	},
	'div.brand_category_title_block' : function(el) {
		//alert(el.innerHeight)
	}
}

Behaviour.register(bjs_brand_store);

/* script app: ../dept_nav/screen.js */
/* script app: ../breadcrumbs/screen.js */
/* script app: ../meal_category_nav/screen.js */
var bjs_brand_store = {
        'form#shop_brand_store_select select' : function(el) {
                el.onchange = function() {
			var id = this.value;
			this.parentNode.action += '&id=' + id;
			this.parentNode.submit();
			return false;
		}
	},
	'div.brand_category_title_block' : function(el) {
		//alert(el.innerHeight)
	}
}

Behaviour.register(bjs_brand_store);

