//** Tab Content script v2.0- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)

//** Updated Oct 7th, 07 to version 2.0. Contains numerous improvements:

//   -Added Auto Mode: Script auto rotates the tabs based on an interval, until a tab is explicitly selected

//   -Ability to expand/contract arbitrary DIVs on the page as the tabbed content is expanded/ contracted

//   -Ability to dynamically select a tab either based on its position within its peers, or its ID attribute (give the target tab one 1st)

//   -Ability to set where the CSS classname "selected" get assigned- either to the target tab's link ("A"), or its parent container

//** Updated Feb 18th, 08 to version 2.1: Adds a "tabinstance.cycleit(dir)" method to cycle forward or backward between tabs dynamically

//** Updated April 8th, 08 to version 2.2: Adds support for expanding a tab using a URL parameter (ie: http://mysite.com/tabcontent.htm?tabinterfaceid=0) 



////NO NEED TO EDIT BELOW////////////////////////



function ddtabcontent(tabinterfaceid){

	this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container

	this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container

	this.enabletabpersistence=true

	this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container

	this.currentTabIndex=0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array

	this.subcontentids=[] //Array to store ids of the sub contents ("rel" attr values)

	this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)

	this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")

}



ddtabcontent.getCookie=function(Name){ 

	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair

	if (document.cookie.match(re)) //if cookie found

		return document.cookie.match(re)[0].split("=")[1] //return its value

	return ""

}



ddtabcontent.setCookie=function(name, value){

	document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)

}



ddtabcontent.prototype={



	expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers

		this.cancelautorun() //stop auto cycling of tabs (if running)

		var tabref=""

		try{

			if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr

				tabref=document.getElementById(tabid_or_position)

			else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr

				tabref=this.tabs[tabid_or_position]

		}

		catch(err){alert("Invalid Tab ID or position entered!")}

		if (tabref!="") //if a valid tab is found based on function parameter

			this.expandtab(tabref) //expand this tab

	},



	cycleit:function(dir, autorun){ //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') )

		if (dir=="next"){

			var currentTabIndex=(this.currentTabIndex<this.hottabspositions.length-1)? this.currentTabIndex+1 : 0

		}

		else if (dir=="prev"){

			var currentTabIndex=(this.currentTabIndex>0)? this.currentTabIndex-1 : this.hottabspositions.length-1

		}

		if (typeof autorun=="undefined") //if cycleit() is being called by user, versus autorun() function

			this.cancelautorun() //stop auto cycling of tabs (if running)

		this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]])

	},



	setpersist:function(bool){ //PUBLIC function to toggle persistence feature

			this.enabletabpersistence=bool

	},



	setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")

		this.selectedClassTarget=objstr || "link"

	},



	getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to

		return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref

	},



	urlparamselect:function(tabinterfaceid){

		var result=window.location.search.match(new RegExp(tabinterfaceid+"=(\\d+)", "i")) //check for "?tabinterfaceid=2" in URL

		return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index

	},



	expandtab:function(tabref){

		var subcontentid=tabref.getAttribute("rel") //Get id of subcontent to expand

		//Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through

		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""

		this.expandsubcontent(subcontentid)

		this.expandrevcontent(associatedrevids)

		for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected"

			this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("rel")==subcontentid)? "selected" : ""

		}

		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers

			ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition)

		this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array

	},



	expandsubcontent:function(subcontentid){

		for (var i=0; i<this.subcontentids.length; i++){

			var subcontent=document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop)

			subcontent.style.display=(subcontent.id==subcontentid)? "block" : "none" //"show" or hide sub content based on matching id attr value

		}

	},



	expandrevcontent:function(associatedrevids){

		var allrevids=this.revcontentids

		for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface

			//if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it

			document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none"

		}

	},



	setcurrenttabindex:function(tabposition){ //store current position of tab (within hottabspositions[] array)

		for (var i=0; i<this.hottabspositions.length; i++){

			if (tabposition==this.hottabspositions[i]){

				this.currentTabIndex=i

				break

			}

		}

	},



	autorun:function(){ //function to auto cycle through and select tabs based on a set interval

		this.cycleit('next', true)

	},



	cancelautorun:function(){

		if (typeof this.autoruntimer!="undefined")

			clearInterval(this.autoruntimer)

	},



	init:function(automodeperiod){

		var persistedtab=ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)

		var selectedtab=-1 //Currently selected tab index (-1 meaning none)

		var selectedtabfromurl=this.urlparamselect(this.tabinterfaceid) //returns null or index from: tabcontent.htm?tabinterfaceid=index

		this.automodeperiod=automodeperiod || 0

		for (var i=0; i<this.tabs.length; i++){

			this.tabs[i].tabposition=i //remember position of tab relative to its peers

			if (this.tabs[i].getAttribute("rel")){

				var tabinstance=this

				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers

				this.subcontentids[this.subcontentids.length]=this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value)

				this.tabs[i].onclick=function(){

					tabinstance.expandtab(this)

					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)

					return false

				}

				if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element

					this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))

				}

				if (selectedtabfromurl==i || this.enabletabpersistence && selectedtab==-1 && parseInt(persistedtab)==i || !this.enabletabpersistence && selectedtab==-1 && this.getselectedClassTarget(this.tabs[i]).className=="selected"){

					selectedtab=i //Selected tab index, if found

				}

			}

		} //END for loop

		if (selectedtab!=-1) //if a valid default selected tab index is found

			this.expandtab(this.tabs[selectedtab]) //expand selected tab (either from URL parameter, persistent feature, or class="selected" class)

		else //if no valid default selected index found

			this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr

		if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){

			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)

		}

	} //END int() function



} //END Prototype assignment
/*

Page:           rating.js

Created:        Aug 2006

Last Mod:       Mar 11 2007

Handles actions and requests for rating bars.	

--------------------------------------------------------- 

ryan masuga, masugadesign.com

ryan@masugadesign.com 

Licensed under a Creative Commons Attribution 3.0 License.

http://creativecommons.org/licenses/by/3.0/

See readme.txt for full credit details.

--------------------------------------------------------- */



var xmlhttp

	/*@cc_on @*/

	/*@if (@_jscript_version >= 5)

	  try {

	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")

	 } catch (e) {

	  try {

	    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")

	  } catch (E) {

	   xmlhttp=false

	  }

	 }

	@else

	 xmlhttp=false

	@end @*/

	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {

	 try {

	  xmlhttp = new XMLHttpRequest();

	 } catch (e) {

	  xmlhttp=false

	 }

	}

	function myXMLHttpRequest() {

	  var xmlhttplocal;

	  try {

	    xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")

	 } catch (e) {

	  try {

	    xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")

	  } catch (E) {

	    xmlhttplocal=false;

	  }

	 }



	if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {

	 try {

	  var xmlhttplocal = new XMLHttpRequest();

	 } catch (e) {

	  var xmlhttplocal=false;

	  alert('couldn\'t create xmlhttp object');

	 }

	}

	return(xmlhttplocal);

}



function sndReq(vote,id_num,ip_num,units) {

	var theUL = document.getElementById('unit_ul'+id_num); // the UL

	

	// switch UL with a loading div

	theUL.innerHTML = '<div class="loading"></div>';

	

    xmlhttp.open('get', 'http://boutique.atelier-poterie.fr/modules/productrating/rating/rpc.php?j='+vote+'&q='+id_num+'&t='+ip_num+'&c='+units);

    xmlhttp.onreadystatechange = handleResponse;

    xmlhttp.send(null);	

}



function handleResponse() {

  if(xmlhttp.readyState == 4){

		if (xmlhttp.status == 200){

       	

        var response = xmlhttp.responseText;

        var update = new Array();



        if(response.indexOf('|') != -1) {

            update = response.split('|');

            changeText(update[0], update[1]);

        }

		}

    }

}



function changeText( div2show, text ) {

    // Detect Browser

    var IE = (document.all) ? 1 : 0;

    var DOM = 0; 

    if (parseInt(navigator.appVersion) >=5) {DOM=1};



    // Grab the content from the requested "div" and show it in the "container"

    if (DOM) {

        var viewer = document.getElementById(div2show);

        viewer.innerHTML = text;

    }  else if(IE) {

        document.all[div2show].innerHTML = text;

    }

}



/* =============================================================== */

var ratingAction = {

		'a.rater' : function(element){

			element.onclick = function(){



			var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');

			var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');

			var parameterList = new Array();



			for (j = 0; j < parameterTokens.length; j++) {

				var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j

				var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1

				parameterList[parameterName] = parameterValue;

			}

			var theratingID = parameterList['q'];

			var theVote = parameterList['j'];

			var theuserIP = parameterList['t'];

			var theunits = parameterList['c'];

			

			//for testing	alert('sndReq('+theVote+','+theratingID+','+theuserIP+','+theunits+')'); return false;

			sndReq(theVote,theratingID,theuserIP,theunits); return false;		

			}

		}

		

	};

Behaviour.register(ratingAction);

/*
   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);
      if (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 {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        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 {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        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
*/

