// *****************************************************************************************
// Script:		js/ajax.js
// Author(s):		Guillaume Lambert - guillaume@falzhobel.ca
//			Alex Gignac - alex@ax2.ca
//
// Date:		Oct 2009
//
// Javascript functions for all AJAX-based calls
//
// Functions:
//	-
//
// *****************************************************************************************

/*
 * function fetchGallery()
 * fetch selected list of thumbs on selected page with ajax/gallery_load.php
 * 
 * params
 * 	@page_num	int	num of chosen page
 *	@item_id	int	item to fetch for
 *	@type		str	based on global typeID
 * 	@work_id	int	jump to specific work
 *	@is_previous	bool	if the page change was init by using previous
 *
 */
	
function fetchGallery(page_num, item_id, type, work_id, is_previous) {
	
	// show loader
	$('browse_thumbs').update('<div id="browse_thumbs_loading"><img src="' + appWebPath + 'images/icons/loader.gif" alt="" /></div>');
	
	// process ajax
	new Ajax.Request(appWebPath + 'ajax/gallery_load.php', {
		
		// parameters sent to ajax in "post" method
		parameters: { page_num: page_num, item_id: item_id, type: type, work_id: work_id },
		
		onSuccess: function(transport) {
			
			// load the response, and convert JSON into regular array
			var response = transport.responseText;
			var jsonObj = response.evalJSON();
			
			// set page_num and work_id with response
			page_num = jsonObj.page_num;
			work_id = jsonObj.work_id;
			
			// var that will hold new content
			var itemsList = '';
			
			// list start
			itemsList += '<ul id="details_browse_thumbs">';
				
			// loop through response array, and populate thumbs
			for (var i = 0; i < jsonObj.works.length; i++) {
				
				// add thumb to output - different div classes depending on rows
				if (i % 2 == 1) {
					itemsList += '<li class="left_pad">';
				} else {
					itemsList += '<li>';
				}
				
				// video for the work?
				work_video = '';
				if (jsonObj.works[i].video != '' && jsonObj.works[i].video_width != 0 && jsonObj.works[i].video_height != 0) {
					work_video = '<p class="video_play"><a href="#' + jsonObj.works[i].id + '" id="thumb' + jsonObj.works[i].id + '"><img src="' + appWebPath + 'images/icons/video_play.png" alt="" border="0" /></a></p>';
				}
				
				itemsList += '<a href="#' + jsonObj.works[i].id + '" id="thumb' + jsonObj.works[i].id + '"><img src="' + jsonObj.works[i].image + '" alt="" border="0" class="gray_border" /></a>' + work_video + '</li>';
			
				// first verify if this was called from a previous link, in this case we must chose last work of the list
				// ** SWFAddress onChange event handles fetchGalleryDetails **
				if (is_previous) {
				
					// when last is reached, show it!
					if (i == (jsonObj.works.length - 1)) {
						current_thumb = '';
						// fetchGalleryDetails(jsonObj.works[i].id, type);
						SWFAddress.setValue('' + jsonObj.works[i].id);
					}
					
				
				} else {
			
					// verify if a work_id was set or not
					if (work_id != 0) {
						// if yes, when loop passes through, show the chosen work
						if (work_id == jsonObj.works[i].id) {
							current_thumb = '';
							// fetchGalleryDetails(work_id, type);
							SWFAddress.setValue('' + work_id);
						}
					} else {
						// else simply set current thumb, swfaddress will take care of loading the work
						if (i == 0) {
							current_thumb = '';
							// fetchGalleryDetails(jsonObj.works[i].id, type);
							SWFAddress.setValue('' + jsonObj.works[i].id);
						}
					}
	
				}	
				
			}
			
			// list end
			itemsList += '</ul>';
			
			// load thumbs into div
			$('browse_thumbs').update(itemsList);
			
			// put "on" class on current page, for both paginations
			$('page' + page_num + '_head').addClassName('page_on');
			$('page' + page_num + '_footer').addClassName('page_on');
						
			// remove "on" class on previous page, for both paginations
			if (current_page != '') { 
				$('page' + current_page + '_head').removeClassName('page_on');
				$('page' + current_page + '_footer').removeClassName('page_on'); 
			}
				
			// update current page var
			current_page = parseInt(page_num);
			
		},
		
		onFailure: function() { alert('Error in communication with server!'); }
		
	});
	
}

/*
 * function fetchGalleryDetails()
 * fetch selected thumb details with ajax/gallery_details_load.php
 * 
 * params
 * 	@thumb_id	int	id of chosen thumb
 *	@type		str	based on global typeID
 *
 */
 
function fetchGalleryDetails(thumb_id, type) {

	// show loader
	$('details_full').update('<div id="details_full_loading"><img src="' + appWebPath + 'images/icons/loader.gif" alt="" /></div>');
	
	// process ajax
	new Ajax.Request(appWebPath + 'ajax/gallery_details_load.php', {
	
		// parameters sent to ajax in "post" method
		parameters: { thumb_id: thumb_id, type: type },
	
		onSuccess: function(transport) {
		
			// load the response, and convert JSON into regular array
			var response = transport.responseText;
			var jsonObj = response.evalJSON();
			
			// modify the add to pdf link for the current item
			//$('add_to_pdf').writeAttribute('href', appWebPath + siteLang + '/pdf-add?id=' + type + '-' + thumb_id);
			$('add_to_pdf').writeAttribute('href', 'javascript:void(0);');
			//$('add_to_pdf').writeAttribute("onclick", "addItemToPdf(" + thumb_id + ", '" + type + "');");
			
			// modify the remove from pdf link for the current item
			$('remove_from_pdf').writeAttribute('href', 'javascript:void(0);');
			//$('remove_from_pdf').writeAttribute("onclick", "removeItemFromPdf('" + type + "-" + thumb_id + "', 'N');");
			
			// determine which link to show
			if (jsonObj.is_in_cart == "Y") {
				// switch add link for remove
				$('add_to_pdf').hide();
				$('remove_from_pdf').show();
			} else {
				// switch remove link for add ...
				$('remove_from_pdf').hide();
				$('add_to_pdf').show();
			}
		
			// var that will hold full content
			full_content = '';
		
			// image or video?
			if (jsonObj.video == '') {
				full_content = '<img src="' + jsonObj.image + '" style="cursor:pointer;" onclick="get_next_work();" alt="" border="0" />';
			} else {
				// display video content
				full_content += '<p id="project_flv"></p>';
				full_content += '<script type="text/javascript">';
				full_content += 'var s1 = new SWFObject(\'' + appWebPath + 'swf/player-licensed.swf\', \'player\', \'' + jsonObj.video_width + '\', \'' + (jsonObj.video_height + 32) + '\', \'8\');';
				full_content += 's1.addParam(\'allowfullscreen\', \'true\');';
				full_content += 's1.addParam(\'allowscriptaccess\', \'always\');';
				full_content += 's1.addParam(\'wmode\',\'opaque\');'
				full_content += 's1.addVariable(\'file\',\'' + jsonObj.video + '\');';
				full_content += 's1.addVariable(\'autostart\',\'true\');';
				full_content += 's1.addVariable(\'skin\',\'' + appWebPath + 'swf/flvskins/modieus.swf\');';
				full_content += 's1.write(\'project_flv\');';
				full_content += '</script>';
				
				// hide PDF buttons
				//$('remove_from_pdf').hide();
				//$('add_to_pdf').hide();
			}
			
			// update details full
			$('details_full').update(full_content);
								
			// update caption
			if (type != 'clinique') {
				$('current_caption').update(jsonObj['caption_' + siteLang]);
			} else {
				var tmp_caption = "";
				tmp_caption += jsonObj['caption_' + siteLang];
				
				if (jsonObj['url'] != "") {
					if (tmp_caption != "") { tmp_caption += " / "; }
					tmp_caption += '<a href="' + jsonObj['url_href'] + '" target="_blank">' + jsonObj['url'] + '</a>';
				}
				
				$('current_caption').update(tmp_caption);
			}
			
			// var for tags
			tag_list = '';
			
			// populate tag list for artists only
			if (type != 'clinique') {
				
				// verify if there is any tags for this work
				if (jsonObj.tags.length > 0) {
				
					// populate tags
					for (var i = 0; i < jsonObj.tags.length; i++) {
						tag_list += '<a href="' + appWebPath + siteLang + '/' + typeLink + '/tags/' + jsonObj.tags[i]['keyname_' + siteLang] + '">' + jsonObj.tags[i]['name_' + siteLang] + '</a> ';
						if (i != (jsonObj.tags.length - 1)) {
							tag_list += '<span class="list_sep">|</span> ';
						}
					}
					
					// show keyword div
					$('current_keywords').show();
				
					// update tag list
					$('current_keywords_list').update(tag_list);
					
				// else hide the keywords div
				} else {
				
					$('current_keywords').hide();
				
				}
				
			}
			
			// just make sure we are not clicking the same thumb before
			if (current_thumb != thumb_id) {
					
				// put "on" class on current item
				$('thumb' + thumb_id).addClassName('thumb_on');
						
				// remove "on" class on previous item
				if (current_thumb != '') { $('thumb' + current_thumb).removeClassName('thumb_on'); }
						
				// update current thumb var
				current_thumb = parseInt(thumb_id);
			}
			
			// disable previous when at start
			if (!$('thumb' + current_thumb).up('li').previous('li') && current_page == 1) {
				$('browse_prev').addClassName('browse_disabled');
			} else {
				$('browse_prev').removeClassName('browse_disabled');
			}
			
			if (jsonObj.video == '') {
				// disable next when reaching end
				if (!$('thumb' + current_thumb).up('li').next('li') && !$('page' + current_page + '_head').next('a[rel=page]')) {
					$('browse_next').addClassName('browse_disabled');
					$('details_full').down('img').setStyle({ cursor: 'default' });
				} else {
					$('browse_next').removeClassName('browse_disabled');
					$('details_full').down('img').setStyle({ cursor: 'pointer' });
				}
			}
			
			// ADD + REMOVE TO PDF LINKS : observe the new link
			var element = $('add_to_pdf');
			element.stopObserving('click');
			element.observe('click', function() {
				addItemToPdf(thumb_id, type);
			});
			
			// ADD + REMOVE TO PDF LINKS : observe the new link
			var element = $('remove_from_pdf');
			element.stopObserving('click');
			element.observe('click', function() {
				tmp_code = type + "-" + thumb_id;
				removeItemFromPdf(tmp_code, "N");
			});
			
			// set deep linking value for swfaddress - onChange behaviour is set in common.js
			// ** THIS IS NOW SET DIRECTLY ON CLICK OF WORKS **
			// SWFAddress.setValue('' + thumb_id);
			
			// change addthis url to reflect chosen thumb urls
			$('addthis_button_el').share.url = 'http://www.colagene.com/' + siteLang + '/' + typeID + '/' + itemKeyname + '#' + thumb_id;
			
			// ok, now ready to run swfaddress onchange
			// swfaddress_start = 1;
					
		},
	
		onFailure: function() { alert('Error in communication with server!'); }
	
	});

}

/*
 * function addItemToPdf()
 * add specified item to shopping cart with ajax/pdf_add.php
 * 
 * params
 * 	@thumb_id	int	id of chosen thumb
 *	@type		str	based on global typeID
 *
 */
 
function addItemToPdf(thumb_id, type) {
	//alert(type + '-' + thumb_id);
	
	// make sure that params are provided
	if (thumb_id == "" || thumb_id == 0 || type == "") {
		return false;
	}
	
	// build the item_code
	var item_code = type + '-' + thumb_id;
	
	// process ajax
	new Ajax.Request(appWebPath + 'ajax/pdf_add.php', {	
		// parameters sent to ajax in "post" method
		parameters: { item_code: item_code },
		
		onSuccess: function(transport) {
		
			// load the response, and convert JSON into regular array
			var response = transport.responseText;
			var jsonObj = response.evalJSON();
			
			//alert(jsonObj.status);
			
			// switch add link for remove
			$('add_to_pdf').hide();
			$('remove_from_pdf').show();
		},
	
		onFailure: function() { alert('Error in communication with server!'); }
	
	});
}

/*
 * function removeItemFromPdf()
 * remove specified item from shopping cart with ajax/pdf_remove.php
 * 
 * params
 * 	@item_code	item key saved in session
 *
 */
 
function removeItemFromPdf(item_code, return_values) {
	
	// make sure that params are provided
	if (item_code == "") {
		return false;
	}
	
	if (return_values != "Y" && return_values != "N") {
		return_values = "N";
	}
	
	// ajax request
	new Ajax.Request(appWebPath + "ajax/pdf_remove.php", {  
		method: "post",
		onLoading: function() { $('activityIndicator').show(); },
		onLoaded: function(){$('activityIndicator').hide();},
		parameters: { item_code: item_code, return_values: return_values },
		onSuccess: function(transport) {
			// either load the list, or change item display (based on return_values = Y/N)
			if (return_values == "Y") {
				// load the response, and convert JSON into regular array
				var response = transport.responseText;
				var jsonObj = response.evalJSON();
				
				// when page is empty then redirect
				if ( jsonObj.length < 1 ) {
					window.location = appWebPath + siteLang + '/pdf';
				}
				
				// loop through response array, and populate all the returned items
				var itemsList = "";
				for (var i = 0; i < jsonObj.length; i++) {
					// load item's id
					var item_id = jsonObj[i].id;
					
					itemsList += '<li id="page_' + item_id + '"><img src="' + jsonObj[i].thumb + '" alt="" class="pdf_image gray_border" /><p class="pdf_delete"><a href="javascript:void(0);" onclick="removeItemFromPdf(\'' + item_id + '\', \'Y\');" class="tiny red"><img src="' + appWebPath + 'images/icons/x_red.gif" alt="" /></a></p></li>';
				} // end for
				
				// load the widget items list
				$('pdf_list').innerHTML = itemsList;
				
			} else {
				// switch remove link for add
				$('remove_from_pdf').hide();
				$('add_to_pdf').show();
			}
		},
		onComplete: function() {
			// reset sortable object for list (based on return_values = Y/N)
			if (return_values == "Y") {
				// create sortable object for list
				Sortable.create('pdf_list', { 
							
					// set options
					handle: 'pdf_image',
					overlap: 'horizontal',
					constraint: false,
								
					// when sort is changed
					onChange: function(item) {  
						// test to show the current item
						//alert(item);					
					},  
								
					// when sort is done
					onUpdate: function(list) {
										
						// test to show the list
						//alert(Sortable.serialize(list));
									
						// ajax request
						new Ajax.Request("ajax/pdf_reorder.php", {  
							method: "post",
							onLoading: function() { $('activityIndicator').show(); },
							onLoaded: function(){$('activityIndicator').hide();},
							parameters: { data: Sortable.serialize(list) },
							onComplete: function(){
								// ...
							}
						});			
					}
											
				});
				
				// add delete link behaviour
				$$('.tags_results p.pdf_delete a').each(function(link) {
					
					// remove text
					if (siteLang == 'en') {
						remove_pdf_link = 'Remove';
					}
					if (siteLang == 'fr') {
						remove_pdf_link = 'Supprimer';
					}
					
					// on mouseover, change icon to text
					Event.observe(link, 'mouseover', function(event) {
						$(link).update(remove_pdf_link);
					});
					
					// reverse effect on mouseout
					Event.observe(link, 'mouseout', function(event) {
						$(link).update('<img src="' + appWebPath + 'images/icons/x_red.gif" alt="" />');
					});
					
				});
				
			}
		}
		
	});	
	
}

/*
 * function fetchPreviews()
 * fetch list of previews for seleced artist with ajax/gallery_previews.php
 * after getting the list, start the thumb rotator
 * 
 * params
 * 	@artist_id	int	num of artist
 * 	@element	str	id of element that will hold previews
 *
 */
 
function fetchPreviews(item_id, element, event) {

	// process ajax
	new Ajax.Request(appWebPath + 'ajax/gallery_previews.php', {
	
		// parameters sent to ajax in "post" method
		parameters: { item_id: item_id, type: typeID },
	
		onSuccess: function(transport) {
	
			// load the response, and convert JSON into regular array
			this.response = transport.responseText;
			this.jsonObj = response.evalJSON();
			
			// create preview and preload list
			this.preview_list = new Array();
			
			// populate tag list in array, and in global preload var
			for (var i = 0; i < this.jsonObj.length; i++) {
				this.preview_list[i] = this.jsonObj[i]['image'];
			}
			
			// get image id that will rotate
			this.image_id = $(element).down('img').id;
			
			// init rotator on load
			this.rotator = {
   				path: 	'',
   				id:   	this.image_id,
				speed:  700,
				bMouse: true,
	    			images: this.preview_list
			}
			
			// start rotator
			dw_Rotator.setup(this.rotator);
	
		}.bind(this),
	
		onFailure: function() { alert('Error in communication with server!'); }
	
	});
	
}

function submitNLform() {
	// check the email value
	var email = $('nl_email').value;
	var form = $('newsletter');
	
	if ( echeck(email) ) {
		form.submit();
	} else {
		$('newsletter_form_error').show();
	}
}