/**
*	Dependences
*
*	Overtext
*	Request.HTML
*	DatePicker
*	Accordian
*	SqueezeBox
* 	FancyUpload
* 	Fx.Scroll
* 	Fx.Transitions
*	ZebraTables
*	MooScroller
*/
function setOvertext() {
	var ovrs = $$('input.overtext,select.overtext,textarea.overtext');
	new OverText(ovrs,{
		poll: true,
		pollInterval: 400
		});
}

function setSqueezeBox() {
	SqueezeBox.initialize({
			sizeLoading: {x: 200, y: 150},
			overlayOpacity: 0.3
	});

	SqueezeBox.assign($$('a.image_lightbox]'));
	$$('a.ajax_lightbox').each(function(el,i) {
		lbx = el.getProperty('lbx') ? el.getProperty('lbx') : 450;
		lby = el.getProperty('lby') ? el.getProperty('lby') : 400;
		SqueezeBox.assign(el,{
			size: {x: lbx, y: lby},
			handler:'ajax',
		});
	});
	$$('a.iframe_lightbox').each(function(el,i) {
			lbx = el.getProperty('lbx') ? el.getProperty('lbx') : 450;
			lby = el.getProperty('lby') ? el.getProperty('lby') : 400;
			SqueezeBox.assign(el,{
				size: {x: lbx, y: lby},
				handler:'iframe',
			});
	});
}

function cycleBackgrounds() {
	var bgs = $$('*[.background-image]');
	bgs.each(function(el,i) {
		el.show();
		if(i != 0) el.set('opacity','0');
	});
	var bg_index = 1;
	var last_bg = bgs[0];

	function nextBg() {
		last_bg.set('tween',{duration:2000}).tween('opacity',0);
		last_bg = bgs[bg_index];
		bgs[bg_index].set('tween',{duration:2000}).tween('opacity',1);
		bg_index++;
		if(bg_index == bgs.length) bg_index = 0;
	}

	inval = nextBg.create({periodical:8000});
	inval();
}



/**
* create a tab structure -
*/
function setTabs() {
	var tabs = $$('*[tab]');		// get all the tab links
	var selected_tab = null;		// the currently selected tab

	var selected_tabs = new Hash();
	var tab_options = new Hash();

	// go through all the found tabs
	if(tabs.length > 0) {
		tabs.each(
			function(el) {
				if(!el.getProperty('default_tab')) {
					if(el.getProperty('tab_style') == 'fade') {
						$(el.getProperty('tab')).setStyle('opacity',0);
					} else {
						$(el.getProperty('tab')).setStyle('display','none');		// if not hide the contents (though they should be hidden using css already)
					}
				} else {
					selected_tabs.set(el.get('tab_group'),el);	// save the selected tab with its tab_group
					$(el.getProperty('tab')).setStyle('display','block');
					$(el.getProperty('tab')).setStyle('opacity',100);
					el.addClass('tab_selected');
				}

				// check for periodical
				if(el.getProperty('transition')) {
					tab_options.set('transition','switch');
				}
				el.set(
					{
						'events' : {
							'mouseover' : function() {		// on mouseover set the pointer and give it some style
											this.setStyle('cursor','pointer');
											this.addClass('tab_selected');
										},
							'mouseout' : function() {		// on mouseout set the cursor to normal and return the style (if it is not selected)
											this.setStyle('cursor','normal');
											if(selected_tabs.get(this.getProperty('tab_group')) != this) this.removeClass('tab_selected');
										},
							'click' : function() {			// on click hide the current, show the chosen and add some style
											if(selected_tabs.get(this.getProperty('tab_group')) != this) {
												if(selected_tabs.get(this.getProperty('tab_group'))) {
													if(this.getProperty('tab_style') == 'fade') {
														$(this.getProperty('tab')).setStyle('display','block').fade('in');
														$(selected_tabs.get(this.getProperty('tab_group')).getProperty('tab')).fade('out');
													} else {
														$(this.getProperty('tab')).setStyle('display','block');
														$(selected_tabs.get(this.getProperty('tab_group')).getProperty('tab')).setStyle('display','none');
													}
													this.addClass('tab_selected');
													selected_tabs.get(this.getProperty('tab_group')).removeClass('tab_selected');
												}
												selected_tabs.set(this.getProperty('tab_group'),this);
											}
										}
							}
					});
			});
	}

	if(tab_options.get('transition') == 'switch') {
		var tab_links=$$("*[tab_group=home_tabs]");	// do a periodical for the homepage tab group
		var int=1;
		function nextTab(){
			tab_links[int].fireEvent("click");
			int++;
			if(int==tab_links.length){
				int=0;
			}
		}

		if(tab_links.length > 0) {
			inval=nextTab.create({periodical:7000});
			inval();
		}
	}
}


function setSubnavs() {
	/* associate sublinks with their parents */
	/* example <a href='#' nav='myDivID' />Navigation</a><div id='myDivID'>Sublinks</div> */

	var linkTimer;		// subnav hide timer
	var currentNav;		// last subnav shown
	var shownNav;
	var shownLink;
	var links = $$('ul#admin_links li','.submenus a.tan','.submenus a.blue');	// get the navigation links with defined subnavs

	links.each(			// go through all the found links
		function(el,i) {
			var subnav = $(el.getProperty('subnav'));	// get the id of the subnav from the attribute 'nav'
			el.store('flag','0');

			if(el.get('class') == 'selected') {
				el.store('flag','1');
				shownNav = subnav;
				shownLink = el;
			}

			if(subnav) {
				subnav.store('nav', el);
				el.addEvents(
					{
						'mouseover': function(){
											if(shownLink) {
												if(shownNav) shownNav.hide();
												shownLink.removeClass('selected');
											}
											$clear(linkTimer);					// clear the linkTimer
											if(currentNav) {
												currentNav.hide();		// hide the previous subnav
												if(currentNav.retrieve('nav') != shownNav) currentNav.retrieve('nav').removeClass('selected');
											}
											el.addClass('selected');	// add the selected class
											el.setStyles({'cursor':'pointer'});
											currentNav = subnav;					// set it globally
											subnav.show();						// show the current subnav
									 },
						'mouseout' : function() {
											linkTimer = (
												function(){
													currentNav.hide();
													if(el != shownNav) currentNav.retrieve('nav').removeClass('selected');
													if(shownLink) {
														shownLink.addClass('selected');
														if(shownNav) shownNav.show();
													}
												}
											).delay(250,currentNav);
									 }
					}
				);

				subnav.addEvents(
					{
						'mouseover' : function() {
										$clear(linkTimer);					// clear the timer
									  },
						'mouseout' :  function() {
										if(currentNav && this.retrieve('nav').retrieve('flag') != '1') {
											linkTimer = (
															function(){
																currentNav.setStyle('display','none');
																if(el != shownNav) currentNav.retrieve('nav').removeClass('selected');
																if(shownLink) {
																	shownLink.addClass('selected');
																	if(shownNav) shownNav.show();
																}
															}
														).delay(250,currentNav);
									  }
								  }
					}
				);
			} else {
				el.addEvents(
					{
						'mouseover': function(){
											if(currentNav) {
												currentNav.hide();		// hide the previous subnav
												if(currentNav.retrieve('nav') != shownNav) currentNav.retrieve('nav').removeClass('selected');
											}
											if(shownLink && shownLink != this) {
												linkTimer = (
															function(){
																if(shownNav) shownNav.hide();
																shownLink.removeClass('selected');
															}
														).delay(50,shownNav);
											}
											el.addClass('selected');	// add the selected class
											el.setStyles({'cursor':'pointer'});
									 },
						'mouseout' : function() {
											el.removeClass('selected');
										}
					}
				);
			}
		}
	);
}


var cbCheck;

var ZebraTable = new Class({
		//implements
		Implements: [Options,Events],

		//options
		options: {
			elements: 'table.list-table',
			cssEven: 'even',
			cssOdd: 'odd',
			cssHighlight: 'highlight',
			cssMouseEnter: 'mo'
		},

		//initialization
		initialize: function(options) {
			//set options
			this.setOptions(options);
			//zebra-ize!
			$$(this.options.elements).each(function(table) {
				this.zebraize(table);
			},this);
		},

		//a method that does whatever you want
		zebraize: function(table) {
			//for every row in this table...
			table.getElements('tr').each(function(tr,i) {
				//check to see if the row has th's
				//if so, leave it alone
				//if not, move on
				if(tr.getFirst().get('tag') != 'th') {
					//set the class for this based on odd/even
					var options = this.options, klass = i % 2 ? options.cssEven : options.cssOdd;
					// kenCode - don't change the class if it is preset to highlight
					if(!tr.hasClass(options.cssHighlight)) tr.addClass(klass);
					//start the events!
					if(tr.getProperty('checkbox')) {
						$(tr.getProperty('checkbox')).addEvent('click',function(e) {
							cbCheck = true;
						});
					}
					tr.addEvents({
						//mouseenter
						mouseenter: function () {
							if(!tr.hasClass(options.cssHighlight)) tr.addClass(options.cssMouseEnter).removeClass(klass);
						},
						//mouseleave
						mouseleave: function () {
							if(!tr.hasClass(options.cssHighlight)) tr.removeClass(options.cssMouseEnter).addClass(klass);
						},
						//click
						click: function() {
							//if it is currently not highlighted
							if(!tr.hasClass(options.cssHighlight)) {
								tr.removeClass(options.cssMouseEnter).addClass(options.cssHighlight);
							} else {
								tr.addClass(options.cssMouseEnter).removeClass(options.cssHighlight);
							}
							if(tr.getProperty('checkbox')) {
								if(!cbCheck) $(tr.getProperty('checkbox')).checked = !$(tr.getProperty('checkbox')).checked;
								cbCheck = false;
							}
						}
					});
				}
			},this);
		}
	});

function setToggles() {
	var els = $$('.toggle');
	if($chk(els)) {
		els.each(function(el,i) {
			el.set(
					{
						'events' : {
							'mouseover' : function() {		// on mouseover set the pointer and give it some style
											this.setStyle('cursor','pointer');
										},
							'mouseout' : function() {		// on mouseout set the cursor to normal and return the style (if it is not selected)
											this.setStyle('cursor','normal');
										},
							'click' : function() {			// on click hide the current, show the chosen and add some style
											new Fx.Reveal($(this.getProperty('target'))).toggle();
										}
						}
					}
			);
		});
	}
}
/**
* set default form text values and make them disappear when the form is selected.
*/
function setTextDefaults() {
	var txts = $$('*[default]');
	txts.each(
		function(el,i) {
			var def = el.get('default');	// get the default value
			el.set(
				{
					'value' : def			// set the default value
				}
			);
			el.addEvents(
				{
					'focus' : function() {
						if(def == 'password') {
							el.set(
								{
									'type' : 'password'
								}
							)
						};
						if(el.get('value') == def) {
							el.set(
								{
									'value' : ''
								}
							)
						};
					},
					'blur' : function() {
						if(def == 'password' && el.get('value') == '') {
							el.set(
								{
									'type' : 'text'
								}
							)
						};
						if(el.get('value') == '') {
							el.set(
								{
									'value' : def
								}
							)
						};
					}
				}
			);
		}
	);
}

function navigationEdit() {
	$('url').addEvent('change',function(e) {
		(this.options[this.selectedIndex].get('value') == 'url') ? $('href').show() : $('href').hide();
	});
	$('url').fireEvent('change');
}

function eventEdit() {
	$('remover').addEvent('change',function(e) {
		(this.checked) ? $('removal_date_container').show() : $('removal_date_container').hide();
	});
	$('remover').fireEvent('change');
}

function mediaEdit() {
	if($('remover')) {
	$('remover').addEvent('click',function(e) {
		$('download_link').hide();
		$('remover').hide();
		$('remove_flag').set('value',1);
	});
	}
	var up = new FancyUpload3.Attach('demo-list', '#demo-attach', {
			path: '../assets/plugins/fancyUpload/source/Swiff.Uploader.swf',
			url: 'media_handler.php?mode=upload_media',
			fileSizeMax: 2 * 1024 * 1024,
			multiple: false,
			verbose: false,

			onSelectFail: function(files) {
				files.each(function(file) {
					new Element('li', {
						'class': 'file-invalid',
						events: {
							click: function() {
								this.destroy();
							}
						}
					}).adopt(
						new Element('span', {html: file.validationErrorMessage || file.validationError})
					).inject(this.list, 'bottom');
				}, this);
			},

			onFileSuccess: function(file,response) {
				var json = new Hash(JSON.decode(response, true) || {});
				if (json.get('status') == '0') {
					file.ui.element.addClass('file-failed');
					file.ui.element.set('html', '<strong>Error:</strong> ' + (json.get('error') ? (json.get('error')) : response));
				} else {
					$('filename').set('value',file.name);
					$('demo-attach').hide();
				}
			},

			onFileError: function(file) {
				file.ui.cancel.set('html', 'Retry').removeEvents().addEvent('click', function() {
					file.requeue();
					return false;
				});

				new Element('span', {
					html: file.errorMessage,
					'class': 'file-error'
				}).inject(file.ui.cancel, 'after');
			},

			onFileRequeue: function(file) {
				file.ui.element.getElement('.file-error').destroy();

				file.ui.cancel.set('html', 'Cancel').removeEvents().addEvent('click', function() {
					file.remove();
					return false;
				});

				this.start();
			}

		});


}

function setDeletes() {
		$$('a[html^=Delete]').each(function(el) {
				el.addClass('delete_link');
		});
}


function setImageScroll() {
	var page_scroll = new Fx.Scroll('product_image_list', {
				wait: false,
				duration:1000,
				transition: Fx.Transitions.Quad.easeInOut
	});
	var product_scroll = new Fx.Scroll('product_scroller', {
				wait: false,
				duration:1000,
				transition: Fx.Transitions.Quad.easeInOut
	});
	if($('pg_next')) {
		/* Next Page */
		$('pg_next').addEvents(
				{
					'click' : function() {
									if($('img_page_'+this.get('target'))) {
										page_scroll.toElement('img_page_'+this.get('target'));
										$('current_page').set('html',this.get('target'));
										$('pg_prev').set('target',(this.get('target')-0)-1);
										this.set('target',(this.get('target')-0)+1);
									}
								 }
				}
			);
		/* Previous Page */
		$('pg_prev').addEvents(
				{
					'click' : function() {
									if($('img_page_'+this.get('target'))) {
										page_scroll.toElement('img_page_'+this.get('target'));
										$('current_page').set('html',this.get('target'));
										$('pg_next').set('target',(this.get('target')-0)+1);
										this.set('target',(this.get('target')-0)-1);
									}
								 }
				}
			);
	}

	/* Next Page */
		$('product_next').addEvents(
				{
					'click' : function() {
									if($('product_'+this.get('target'))) {
										product_scroll.toElement('product_'+this.get('target'));

										// get 4 down
										var downtarget = this.get('target')-4 >= this.get('target_min') && this.get('target')-4 <= this.get('target_max') ? this.get('target')-4 : this.get('target_min');

										// get 4 up
										var uptarget = ((this.get('target')-0)+4) <= this.get('target_max')-10 && ((this.get('target')-0)+4) >= this.get('target_min') ? ((this.get('target')-0)+4) : this.get('target_max')-9;

										$('product_prev').set('target',downtarget);
										this.set('target',uptarget);
									}
								 }
				}
			);
		/* Previous Page */
		$('product_prev').addEvents(
				{
					'click' : function() {
									if($('product_'+this.get('target'))) {
										product_scroll.toElement('product_'+this.get('target'));

										// get 4 down
										var downtarget = this.get('target')-4 >= this.get('target_min') && this.get('target')-4 <= this.get('target_max') ? this.get('target')-4 : this.get('target_min');

										// get 4 up
										var uptarget = ((this.get('target')-0)+4) <= this.get('target_max')-10 && ((this.get('target')-0)+4) >= this.get('target_min') ? ((this.get('target')-0)+4) : this.get('target_max')-9;

										$('product_next').set('target',uptarget);
										this.set('target',downtarget);
									}
								 }
				}
		);


	/* Image Swaps */
	$$('*[target_src]').each(function(el,i) {
		el.addEvents({
			'click' : function(e) {
				//$(this.get('target')).set('src',this.get('target_src'));
				imageViewer.remote('loadImage',this.get('target_src'));
				$('image_title').set('html',this.get('title'));
				$('image_id').set('value',this.get('image_id'));
			}
		})
	});
}

function preScrollImages(thumbID) {
	var product_scroll = new Fx.Scroll('product_scroller', {
				wait: false,
				duration:1000,
				transition: Fx.Transitions.Quad.easeInOut
	});
	product_scroll.toElement('product_'+thumbID);

	// get 4 down
	var downtarget = thumbID-4 >= $('product_prev').get('target_min') && thumbID-4 <= $('product_prev').get('target_max') ? thumbID-4 : $('product_prev').get('target_min');

	// get 4 up
	var uptarget = ((thumbID-0)+4) <= $('product_prev').get('target_max')-10 && ((thumbID-0)+4) >= $('product_prev').get('target_min') ? ((thumbID-0)+4) : $('product_prev').get('target_max')-9;

	$('product_next').set('target',uptarget);
	$('product_prev').set('target',downtarget);
}

function checkIfEmpty(field,error) {
	if($(field).get('value') == '') {
		$(field).setStyles({
			'background-color' : '#e7b6b6'
			});
		return error+'<br />';
	} else {
		$(field).setStyles({
					'background-color' : '#FFF'
			});
		return '';
	}
}

function checkForm() {
	var err = '';
	err += checkIfEmpty('c_company','Company is required');
	err += checkIfEmpty('c_name','Name is required');
	err += checkIfEmpty('c_email','Email is required');
	err += checkIfEmpty('c_address','Address is required');
	err += checkIfEmpty('c_phone','Phone is required');

	if(err) {
		$('error_msg').set('html',err);
		$('error_msg').setStyle('display','block');
		return false;
	}
}

function checkoutConfirm() {
	var err='';
	err += checkIfEmpty('name','Name is required');
	err += checkIfEmpty('email','Email is required');
	err += checkIfEmpty('phone','Phone is required');
	err += checkIfEmpty('address','Address is required');
	if(err) {
		err = '<p>Your submission could not be sent because an error has occured. Please update the following information.</p>'+err;
		var clientError = new Element('div',{'html' : err,'id' : 'client_error'}).inject($(document.body),'top');
		SqueezeBox.open($('client_error'), {
			handler: 'adopt',
			size: {x: $('client_error').getSize().x,y:$('client_error').getSize().y}
		});
		return false;
	}
}


// Set tabs to scroll to an overflowed element
function setScrollTabs() {
	var scrollers = $$('*[scroller]');
	var scroller = scrollers[0].get('scroller');
	var current_tab;

	var page_scroll = new Fx.Scroll(scroller, {
				wait: false,
				duration:1000,
				transition: Fx.Transitions.Quad.easeInOut,
				offset: {
					x: -72,
					y: 0
				}
	});

	scrollers.each(function(el,i) {
			el.addEvents({
					'mouseover' : function(e) {
						this.addClass('tab_selected');
					},
					'mouseout' : function(e) {
						if(current_tab != this) this.removeClass('tab_selected');
					},
					'click' : function(e) {
						page_scroll.toElement(this.get('target'));
						this.addClass('tab_selected');
						if(current_tab) current_tab.removeClass('tab_selected');
						current_tab = this;
					}
			});
			if(i==0) {
				el.fireEvent('click');
			}
	});
}

function setImageViewer(imageUrl,imgSrc) {
				imageViewer = new Swiff(imageUrl+'viewers/imageViewer.swf',{
					width: 420,
					height: 234,
					container: $('swfContainer'),
					vars: {imgSrc: imgSrc}
				});
}