//currency buttons

window.addEvent('domready', function() {

	elements = $$('.currBtn');

	elements.each(function(element, i) {

		onMouseOver = element.getProperty('rel');

		onMouseOut = element.getProperty('src');

		element.store('clicked', 'false');

		element.store('onMouseOver', onMouseOver);

		element.store('onMouseOut', onMouseOut);		

		element.addEvent('mouseenter', function(){

			if($(this).retrieve('clicked') == 'false')

				this.src =  $(this).retrieve('onMouseOver');

		}); 

		element.addEvent('mouseleave', function(){

			if($(this).retrieve('clicked') == 'false')

				this.src =  $(this).retrieve('onMouseOut');

		});

		element.addEvent('click', function(){

			setBtn(this, 'currBtn');

			id = this.getProperty('id');

			makeAjaxRequest(null, id, null, null);

		});  

	});



});



//metal buttons

window.addEvent('domready', function() {

	elements = $$('.metBtn');

	elements.each(function(element, i) {

		onMouseOver = element.getProperty('rel');

		onMouseOut = element.getProperty('src');

		element.store('clicked', 'false');

		element.store('onMouseOver', onMouseOver);

		element.store('onMouseOut', onMouseOut);		

		element.addEvent('mouseenter', function(){

			if($(this).retrieve('clicked') == 'false')

				this.src =  $(this).retrieve('onMouseOver');

		}); 

		element.addEvent('mouseleave', function(){

			if($(this).retrieve('clicked') == 'false')

				this.src =  $(this).retrieve('onMouseOut');

		});

		element.addEvent('click', function(){

			setBtn(this, 'metBtn');

			id = this.getProperty('id');

			makeAjaxRequest(id, null, null, null);

		});  

	});



});







/* creates graph layers */

window.addEvent('domready', function() {

	if(!$defined($('FactorySumDiv'))){

		var Div = new Element('div',{

    			'id': 'FactorySumDiv', 

    			'style' : {

       			'text-align': 'center'

    			},

    			'html': ''

		});

		$('graphAjax').adopt(Div);

	}

	new Request({

			url: '/portal/index.php?id=1645',

			method: 'get', 

			link: 'cancel',

			onSuccess: function(responseText, responseXML){

						setData(responseText, responseXML);

					},

			onRequest: function(responseText, responseXML) {

						if(!$defined($('spinImg'))){

							$('FactorySumDiv').set('html', '');

							var Img = new Element('img',{

    								'id': 'spinImg',

    								'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 

							});

							$('FactorySumDiv').adopt(Img);					

						}

						if(!$defined($('spinImg2'))){

							$('chartAjax').set('html', '');

							var Img = new Element('img',{

    								'id': 'spinImg2',

    								'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 

							});

							$('chartAjax').adopt(Img);					

						}

					},

			onFailure: function(responseText, responseXML){

						alert('Błąd ładowania danych');

			},

			async: true 

		}).send();

});



function setBtn(el, btn){

	elements = $$('.' + btn);

	elements.each(function(element, i) {

		onMouseOut = $(element).retrieve('onMouseOut');

		element.src =  onMouseOut;

		$(element).store('clicked', 'false'); 

	});

	onMouseOver = $(el).retrieve('onMouseOver');

	$(el).src = onMouseOver; 

	$(el).store('clicked', 'true');

}



function makeAjaxRequest(Type, Curr, DateStart, DateEnd){

	if(Type) $('graphAjax').store('Type', Type);

	else Type = $('graphAjax').retrieve('Type', '');

	if(Curr) $('graphAjax').store('Curr', Curr);

	else Curr = $('graphAjax').retrieve('Curr', '');

	if(DateStart) $('graphAjax').store('DateStart', DateStart);

	else DateStart = $('graphAjax').retrieve('DateStart', '');

	if(DateEnd) $('graphAjax').store('DateEnd', DateEnd);

	else DateEnd = $('graphAjax').retrieve('DateEnd', '');





	var dateItems = DateStart.split ('-');

	var year = parseInt (dateItems[0], 10);	

	var month = parseInt(dateItems[1], 10)-1;

	var day = parseInt (dateItems[2], 10);



	var dStart = new Date(year, month, day);

	dStart = dStart.getTime();



	var dateItems = DateEnd.split ('-');

	var year = parseInt (dateItems[0], 10);	

	var month = parseInt(dateItems[1], 10)-1;

	var day = parseInt (dateItems[2], 10);	



	var dEnd = new Date(year, month, day);

	dEnd = dEnd.getTime();	



	var now = new Date();

	now = now.getTime();

	if(dEnd > now){

		alert('Data końcowa nie może być większa od daty dzisiejszej');

		return;

	}

	if(dStart >= dEnd){

		alert('Data początkowa musi być mniejsza od końcowej');

		return;

	}

 	

//alert('Type=' +Type+ '&Curr=' +Curr+ '&DateStart=' +DateStart+ '&DateEnd=' +DateEnd);

	new Request({

			url: '/portal/index.php?id=1645',

			method: 'get', 

			data: '',

			link: 'cancel',

			onSuccess: function(responseText, responseXML){

						setData(responseText, responseXML);

					},

			onRequest: function(responseText, responseXML) {

						if(!$defined($('spinImg'))){

							$('FactorySumDiv').set('html', '');

							var Img = new Element('img',{

    								'id': 'spinImg', 

    								'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 

							});

							$('FactorySumDiv').adopt(Img);					

						}

						if(!$defined($('spinImg2'))){

							$('chartAjax').set('html', '');

							var Img = new Element('img',{

    								'id': 'spinImg2',

    								'src': 'assets/templates/enumizmatyka/images/bg/spin.gif' 

							});

							$('chartAjax').adopt(Img);					

						}

					},

			onFailure: function(responseText, responseXML){

						alert('Błąd ładowania danych');

			},

			async: true 

		}).send('Type=' +Type+ '&Curr=' +Curr+ '&DateStart=' +DateStart+ '&DateEnd=' +DateEnd);

}



function roundNumber(num, dec) {

	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);

	return result;

}



function removeLineBreaks(string) { 

  return string.replace('\n', '/'); 

} 



function setData(responseText, responseXML){//alert(responseText);

	eval('JSONData = (' + responseText + ')');

	var txt = '';

	var Curr = $('graphAjax').retrieve('Curr', '');

	switch(Curr){

		case 'USD':

			prefix = '$';

			break;

		case 'GBP':

			prefix = '&#163;';

			break;

		case 'EURO':

			prefix = '&#8364;';

			break;

		default:

			Curr = 'USD';

			prefix = '$';

			break;



	}

        prefix='';


	txt += "<chart palette='2'  showLimits='0'  caption='' xAxisName='' showValues='0' setAdaptiveYMin='1' bgColor='#FFFFFF' baseFontColor='#006F93' lineColor='#FF0000' lineThickness='3' divLineColor='#ADAAAA' numVDivLines='10' divLineThickness='1' divLineAlpha='20' alternateHGridColor='#CFCFCF' alternateHGridAlpha='10' canvasBorderColor='#E0E0E0' canvasBorderThickness='1'  showBorder='0'  drawAnchors='1' anchorAlpha='100' chartLeftMargin='20' chartTopMargin='1' chartRightMargin='20' chartBottomMargin='1' numberPrefix='" + prefix + "'>";



	step = Math.ceil(JSONData.data.length / 7);

	JSONData.data.each(function(item, index){



		if((index == 0 || index == JSONData.data.length - 1 || (index % step == 0 && (JSONData.data.length - 1 - index) > step / 2)) && $defined(item)){

			txt += "<set label='" +item.Date+ "' value='" +item.Value+ "' anchorBgColor='FFFFFF' anchorBorderColor='000000' anchorBorderThickness='1' toolText='" + removeLineBreaks(item.Date) + " "+ roundNumber(item.Value, 2) + prefix +"' />";

		}

		else

			txt += "<set label='' value='" +item.Value+ "' toolText='" + removeLineBreaks(item.Date) + " "+ roundNumber(item.Value, 2) + prefix +"' anchorAlpha='0' />";		

	});

	

	txt += "<styles>";

      txt += "  <definition>";

      txt += "      <style name='myAnim1' type='animation' param='_xScale' start='0' duration='1'/>";

      txt += "      <style name='myAnim2' type='animation' param='_alpha' start='0' duration='1'/>";

      txt += "  </definition>";

      txt += "  <application>"

      txt += "      <apply toObject='HGRID' styles='myAnim1, myAnim2' />";

      txt += "      <apply toObject='DIVLINES' styles='myAnim1' />";

      txt += "  </application>";

   	txt += " </styles>";

	txt += "</chart>";



	//Finally, render the chart.

	chart_FactorySum = new FusionCharts("assets/flash/FusionCharts_Developer/Charts/Line.swf", "FactorySum", "520", "240", "0", "0");

	chart_FactorySum.setDataXML(txt);

	chart_FactorySum.addParam('WMode', 'opaque');

	chart_FactorySum.render("FactorySumDiv");



	txt = '';

	txt += '<table cellspacing="0" cellpadding="5" border="0" width="500">';

	txt += '	<tr>';

	txt += '		<th width="14%"><strong>Data</strong></th>';

	txt += '		<th width="14%"><strong>' +Curr+ ' AM</strong></th>';

	txt += '		<th width="14%"><strong>Trend</strong></th>';

	txt += '		<th width="14%"><strong>' +Curr+ ' PM</strong></th>';

	txt += '		<th width="14%"><strong>Trend</strong></th>';

	txt += '	</tr>';



	step = Math.ceil(JSONData.table.length / 20);

	pointer = 0;

	JSONData.table.reverse();



	JSONData.table.each(function(item, index){

		if((index == 0 || index == JSONData.data.length - 1 || index % step == 0) && $defined(item)){

			var className = pointer % 2 == 0 ? 'subListOdd' : 'subList';

			txt += '	<tr>';

			txt += '		<td width="14%" class="' +className+ '">' + item.Date + '</td>';

			txt += '		<td width="14%" class="' +className+ '">' + item.valueAM + ' </td>';

			if(item.trendImgAM  != '' && item.trendValueAM != '')

				txt += '		<td width="14%" class="' +className+ '"><img src="' + item.trendImgAM + '" border="0" />&nbsp;&nbsp;' + item.trendValueAM + '</td>';

			else

				txt += '		<td width="14%" class="' +className+ '">&nbsp;</td>';			

			txt += '		<td width="14%" class="' +className+ '">' + item.valuePM + '</td>';

			if(item.trendImgPM  != '' && item.trendValuePM != '')

				txt += '		<td width="14%" class="' +className+ '"><img src="' + item.trendImgPM + '" border="0" />&nbsp;&nbsp;' + item.trendValuePM + '</td>';

			else

				txt += '		<td width="14%" class="' +className+ '">&nbsp;</td>';	

			txt += '	</tr>';

			pointer++;

		}

	});	



	txt += '</table>';

 	$('chartAjax').set('html', txt);

}





window.addEvent('domready', function() {

var mySlide = new Slider($('area'), $('knob'), {

    //options

	range: [0, 1430],

	snap: false,

	steps: 10,

	offset: 0,

	wheel: false,

	mode: 'horizontal',

 

	//callback events

    onChange: function(step){



    },

    onTick: function(pos){

 

    },

    onComplete: function(step){

		var DateEnd = new Date();

		mseconds = DateEnd.getTime();

		var DateStart = new Date();



		DateStart.setTime(mseconds - (parseInt(step) + 30) * 24 * 60 * 60 * 1000);

		DateStart = DateStart.getFullYear() + '-' + (DateStart.getMonth() + 1) + '-' + DateStart.getDate();

		DateEnd = DateEnd.getFullYear() + '-' + (DateEnd.getMonth() + 1) + '-' + DateEnd.getDate();

		document.forms['val'].DateStart.value = DateStart;

		document.forms['val'].DateEnd.value = DateEnd;

		makeAjaxRequest(null, null, DateStart, DateEnd);



    }

}).set(0);

});



window.addEvent('domready', function() {

	calculateMetal(document.forms['calculator']);

});



function calculateMetal(form){

	Reg = /^[0-9]{1,}(\.[0-9]+)?$/;

	Type = form.Type.options[form.Type.selectedIndex].value;

	Currency = form.Currency.options[form.Currency.selectedIndex].value;

	Weight = form.Weight.options[form.Weight.selectedIndex].value;

	Qty = form.Qty.value; 

	Carat = form.Carat.options[form.Carat.selectedIndex].value;



	if(Reg.test(Qty) != true){

		alert('Ilość musi być liczbą');

		return;

	}

	else if(Qty <= 0){

		alert('Ilość musi być większa od zera');

		return;

	}





	new Request({

			url: '/portal/index.php?id=1652',

			method: 'get', 

			data: '',

			link: 'cancel',

			onSuccess: function(responseText, responseXML){

						eval('JSONData = (' + responseText + ')');

						$('calResult').set('html', JSONData.Rate);

						$('spotResult').set('html', JSONData.Time);

					},

			onRequest: function(responseText, responseXML) {

							$('calResult').set('html', 'trwa ładowanie...');

							$('spotResult').set('html', '');

					},

			onFailure: function(responseText, responseXML){

						alert('Błąd ładowania danych');

			},

			async: true 

		}).send('Type=' +Type+ '&Currency=' +Currency+ '&Weight=' +Weight+ '&Qty=' +Qty + '&Carat=' + Carat);



	return;	

}



Calendar._DN = new Array ("Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela");Calendar._SDN = new Array ("N", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "N"); Calendar._FD = 0;	Calendar._MN = new Array ("Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień");	Calendar._SMN = new Array ("Sty", "Lut", "Mar", "Kwi", "Maj", "Cze", "Lip", "Sie", "Wrz", "Paź", "Lis", "Gru");Calendar._TT = {};Calendar._TT["INFO"] = "O kalendarzu";

 		Calendar._TT["ABOUT"] =

 "DHTML Date/Time Selector\n" +

 "(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +

"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +

"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +

"\n\n" +

"Date selection:\n" +

"- Use the \xab, \xbb buttons to select year\n" +

"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +

"- Hold mouse button on any of the above buttons for faster selection.";

Calendar._TT["ABOUT_TIME"] = "\n\n" +

"Time selection:\n" +

"- Click on any of the time parts to increase it\n" +

"- or Shift-click to decrease it\n" +

"- or click and drag for faster selection.";



		Calendar._TT["PREV_YEAR"] = "Przyciśnij, by przejść do poprzedniego roku. Przyciśnij i przytrzymaj, by przejść do listy lat.";Calendar._TT["PREV_MONTH"] = "Przyciśnij, by przejść do poprzedniego miesiąca. Przyciśnij i przytrzymaj, by przejść do listy miesięcy.";	Calendar._TT["GO_TODAY"] = "Ustaw obecną datę";Calendar._TT["NEXT_MONTH"] = "Przyciśnij, by przejść do następnego miesiąca. Przyciśnij i przytrzymaj, by przejść do listy miesięcy.";Calendar._TT["NEXT_YEAR"] = "Przyciśnij, by przejść do następnego roku. Przyciśnij i przytrzymaj, by przejść do listy lat.";Calendar._TT["SEL_DATE"] = "Wybierz datę";Calendar._TT["DRAG_TO_MOVE"] = "Przyciśnij i przeciągnij, by przesunąć";Calendar._TT["PART_TODAY"] = "(Dziś)";Calendar._TT["DAY_FIRST"] = "Najpierw %s";Calendar._TT["WEEKEND"] = "0,6";Calendar._TT["CLOSE"] = "Zamknij";Calendar._TT["TODAY"] = "Dzisiaj";Calendar._TT["TIME_PART"] = "Shift+ Przyciśnij lub przeciągnij, by zmienić wartość.";Calendar._TT["DEF_DATE_FORMAT"] = "%D-%M-%Y"; Calendar._TT["TT_DATE_FORMAT"] = "%A, %e %B";Calendar._TT["WK"] = "wk";Calendar._TT["TIME"] = "Czas:";



window.addEvent('domready', function() {Calendar.setup({

        inputField     :    "DateStart",     // id of the input field

        ifFormat       :    "%Y-%m-%d",      // format of the input field

        button         :    "DateStartImg",  // trigger for the calendar (button ID)

        align          :    "Tl",           // alignment (defaults to "Bl")

        singleClick    :    true,

	  onUpdate        :   function(){}

    });});

window.addEvent('domready', function() {Calendar.setup({

        inputField     :    "DateEnd",     // id of the input field

        ifFormat       :    "%Y-%m-%d",      // format of the input field

        button         :    "DateEndImg",  // trigger for the calendar (button ID)

        align          :    "Tl",           // alignment (defaults to "Bl")

        singleClick    :    true,

	  onUpdate        :   function(){}

    });});




