/*
	name			: ClassBehaviours, the javascript framework based on class-name parsing
	update			: 9.11.9
	author			: Maurice van Creij
	dependencies	: jquery.classbehaviours.js
	info			: http://www.classbehaviours.com/

    This file is part of jQuery.classBehaviours.

    ClassBehaviours is a javascript framework based on class-name parsing.
    Copyright (C) 2008  Maurice van Creij

    ClassBehaviours is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    ClassBehaviours is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with ClassBehaviours. If not, see http://www.gnu.org/licenses/gpl.html.
*/

	// create the jQuery object if it doesn't already exist
	if(typeof(jQuery)=='undefined') jQuery = function(){};

	// create the root classbehaviours object if it doesn't already exist
	if(typeof(jQuery.classBehaviours)=='undefined') jQuery.classBehaviours = function(){};

	// create the handlers child object if it doesn't already exist
	if(typeof(jQuery.classBehaviours.handlers)=='undefined') jQuery.classBehaviours.handlers = function(){}

	// move a link's click event to the parent node
	jQuery.classBehaviours.handlers.auctionCounter = {
		// properties
		name: 'auctionCounter',
		interval: null,
		timeout: null,
		node: null,
		xml: null,
		index: 0,
		// methods
		start: function(node){
			// store the current node
			this.node = node;
			// get the initial config
			initialConfigXml = node.innerHTML.split('**config**')[1];
			initialConfigDom = jQuery.classBehaviours.ajax.deserialize2(initialConfigXml);
			// set the initial calculation
			this.load(initialConfigDom, node, initialConfigXml);
		},
		// events
		wait: function(waitStatus, waitNode, waitError){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			// progress indicator
		},
		load: function(loadXML, loadNode, loadTxt){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			// store the data
			acn.node = loadNode;
			acn.xml = loadXML;
			// cancel the old delays
			clearInterval(acn.interval);
			clearTimeout(acn.timeout);
			// check if a reloadFromURL is required
			reloadRequired = (loadXML.getElementsByTagName('action')[0].getAttribute('refresh')=='1');
			if(reloadRequired){
				acn.reset();
			}else{
				// get the timeout settings numbers
				intervalDelay = parseInt(loadXML.getElementsByTagName('action')[0].getAttribute('discountinterval')) * 1000;
				timeoutDelay = parseInt(loadXML.getElementsByTagName('action')[0].getAttribute('serviceinterval')) * 1000;
				// set the delay for the updates
				acn.interval = setInterval("jQuery.classBehaviours.handlers.auctionCounter.update()", intervalDelay);
				// set the delay for the reload
				acn.timeout = setTimeout("jQuery.classBehaviours.handlers.auctionCounter.reload()", timeoutDelay);
			}
		},
		update: function(){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			// get the decimal setting
			decimalChar = acn.xml.getElementsByTagName('action')[0].getAttribute('decimalseperator');
			thousandsChar = (decimalChar=='.') ? ',' : '.';
			// get the original time
			originalTime = new Date(acn.xml.getElementsByTagName('action')[0].getAttribute('timestamp'));
			// get the time difference
			timeDifference = Math.round((new Date() - originalTime) / 1000);
			// for all nodes in the config
			allProducts = acn.xml.getElementsByTagName('product');
			zeroPrice = false;
			for(var a=0; a<allProducts.length; a++){
				// calculate the current price
				oldPrice = parseFloat(allProducts[a].getAttribute('price'));
				priceDelta = parseFloat(allProducts[a].getAttribute('discount'));
				priceLimit = parseFloat(allProducts[a].getAttribute('pricelimit'));
				canBuy = allProducts[a].getAttribute('canbuy');
				newPrice = oldPrice - priceDelta / 100 * timeDifference;
				if(newPrice<=priceLimit || canBuy=='0') zeroPrice = true;
//if(newPrice<=0) debug(a, oldPrice, newPrice, originalTime);
				// update the price marker
				productObject = document.getElementById('product' + allProducts[a].getAttribute('id'));
				productObject.getElementsByTagName('DIV')[2].innerHTML = (newPrice>=0) ? jQuery.classBehaviours.utilities.makeIntoCurrency(newPrice, decimalChar, thousandsChar)+'\r\n' : '' ;
				productObject.getElementsByTagName('P')[0].getElementsByTagName('SPAN')[0].innerHTML = allProducts[a].getAttribute('time');
				productObject.getElementsByTagName('P')[0].getElementsByTagName('SPAN')[1].innerHTML = allProducts[a].getAttribute('factor');
			}
			// if any price reached 0
			if(zeroPrice){
				// reload the whole application
//debug('zero price');
				acn.reset();
			}
		},
		reload: function(){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			// get a new config xml from the webservice
			url = acn.node.getElementsByTagName('INPUT')[0].value + '&rnd=' +acn.index++;
			jQuery.classBehaviours.ajax.addRequest(url, acn.load, acn.wait, null, acn.node);
		},
		reset: function(){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			// cancel all the timeouts
			clearInterval(acn.interval);
			clearTimeout(acn.timeout);
			// get a new config xml from the webservice
			url = acn.node.getElementsByTagName('INPUT')[1].value + '&rnd=' +acn.index++;
			jQuery.classBehaviours.ajax.addRequest(url, acn.resetLoad, acn.resetWait, null, acn.node);
		},
		resetWait: function(waitStatus, waitNode, waitError){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			// progress indicator
		},
		resetLoad: function(loadXML, loadNode, loadTxt){
			var acn = jQuery.classBehaviours.handlers.auctionCounter;
			acn.node.innerHTML = loadTxt.split('<!-- **cuthere** -->')[1];
			jQuery.classBehaviours.parser.parseNode(acn.node);
		}
	}

	// add this addon to the jQuery object
	if(typeof(jQuery.fn)!='undefined'){
		// extend jQuery with this method
		jQuery.fn.auctionCounter = function(){
			return this.each(
				function(){
					jQuery.classBehaviours.handlers.auctionCounter.start(this);
				}
			);
		};
		// set the event handler for this jQuery method
		$(document).ready(
			function(){
				$(".auctionCounter").auctionCounter();
			}
		);
	}

