// *****************************************************************************************
// Script:		js/common.js
// Author(s):		Guillaume Lambert - guillaume@falzhobel.ca
// 			Alex Gignac - alex@ax2.ca
//
// Common javascript functions including dom-ready commands
//
// Functions:
//	-
//
// *****************************************************************************************

/*
 * function anti_spam_email()
 * function to prevent spambots from getting email address in mailto format
 * 
 */

function anti_spam_email(user, domain, linktext) {
	var username = user;
	var hostname = domain;
	if (linktext == '') {
		linktext = username + "&#064;" + hostname;
	}
	document.write("<a href=" + "mail" + "to:" + username +"&#064;" + hostname + ">" + linktext + "</a>");
}

/*
 * function open_window()
 * opens popup with a list of params
 * 
 */

function open_window(page_url, page_name, window_width, window_height, scrollbar_value, is_center) {
        var window_pos_x = 20;
        var window_pos_y = 20;
        if (is_center == 'yes') {
        	window_pos_x = (screen.width / 2) - (window_width / 2);
        	window_pos_y = (screen.height / 2) - (window_height / 2);
        }
        popup_window = this.open(page_url, page_name, "toolbar=no,status=no,menubar=no,location=no,scrollbars=" + scrollbar_value + ",resizable=no,width=" + window_width + ",height=" + window_height + ",screenX=" + window_pos_x + ",screenY=" + window_pos_y + ",left=" + window_pos_x + ",top=" + window_pos_y);
        popup_window.resizeTo(window_width + 6, window_height + 54);
        popup_window.focus();
}

/*
 * function show_hide_default_val()
 * function to show/hide values in a given form input text
 * 
 */

function show_hide_default_val(action, input, default_val) {
	input_name = document.getElementById(input);
	if (action == 'focus') {
		if (input_name.value == default_val) {
			input_name.value = '';
		}
	}
	if (action == 'blur') {
		if (input_name.value == '') {
			input_name.value = default_val;
		}
	}
}

/*
 * function create_country_tip()
 * based on prototip.js, create country choice tip
 * 
 */
 
function create_country_tip() {

	// init content var
	var tip_content = '';
	
	// fill content
	tip_content += '<a href="/switch_region?id=CA">Canada</a>';
	tip_content += '<a href="/switch_region?id=FR">France</a>';
	tip_content += '<a href="/switch_region?id=UK">United Kingdom</a>';
	tip_content += '<a href="/switch_region?id=US">United States</a>';
	tip_content += '<a href="/switch_region">Other / Autre</a>';
	
	// create tooltip
	$('header_country').tip = new Tip('header_country', tip_content, { 
		style: 'default',
		width: 110 
	});

}

/*
 * function create_lang_tip()
 * based on prototip.js, create lang choice tip
 * 
 */
 
function create_lang_tip() {

	// init content var
	var tip_content = '';
	
	// fill content, depending on lang (on/off)
	if (siteLang == 'fr') {
		tip_content += '<a href="' + langSwitch + '">EN</a>';
		tip_content += 'FR';
	}
	if (siteLang == 'en') {
		tip_content += 'EN';
		tip_content += '<a href="' + langSwitch + '">FR</a>';
	}
	
	// create tooltip
	$('header_choice').tip = new Tip('header_choice', tip_content, { 
		style: 'default',
		width: 'auto' 
	});
	
}

/*
 * function attach_tag_event()
 * attach mouseover event for tag div
 * 
 */
 
function attach_tag_event() {

	// observe sub nav link for tags
	Event.observe('illustration_sub_nav_toggle', 'mouseover', function(event) { $('tags_container').show(); });
	Event.observe('illustration_sub_nav_toggle', 'mouseout', function(event) { $('tags_container').hide(); });

	// duplicate event on shown div to keep it visible
	Event.observe('tags_container', 'mouseover', function(event) { $('tags_container').show(); $('illustration_sub_nav_toggle').addClassName('tags_on'); });
	Event.observe('tags_container', 'mouseout', function(event) { $('tags_container').hide(); $('illustration_sub_nav_toggle').removeClassName('tags_on'); });

}

/*
 * function attach_nav_previews()
 * attach mouseover tooltip event on nav for previews
 * 
 */
 
function attach_nav_previews() {
	
	// loop each sub nav links with a rel attribute
	$$('.main_sub_nav a[rel]').each(function(element) {
    		new Tip(element, {
  			style: 'artists',
  			ajax: {
				url: appWebPath + 'ajax/tooltip_previews.php',
				options: {
					parameters: { item_id: element.rel, type: typeID },
					onComplete: function(transport) {
						// ...
					}
				}
			}
		});
  	});
  	
}

/*
 * function attach_similar_previews()
 * attach mouseover tooltip event on similar artists
 * 
 */

function attach_similar_previews() {

	$$('#current_may_like a[rel]').each(function(element) {
    		new Tip(element, {
  			style: 'similar',
  			ajax: {
				url: appWebPath + 'ajax/tooltip_previews.php',
				options: {
					parameters: { item_id: element.rel, type: typeID },
					onComplete: function(transport) {
						// ...
					}
				}
			}
		});
  	});

}

/*
 * function get_previous_work()
 * get previous work by invoking fetchGalleryDetails() function
 * 
 */

function get_previous_work() {

	// verify if there is a previous item	
	if ($('thumb' + current_thumb).up('li').previous('li')) {
		prev_thumb = $('thumb' + current_thumb).up('li').previous('li').down('a').id.replace('thumb', '');
		// fetchGalleryDetails(prev_thumb, typeID);
		SWFAddress.setValue('' + prev_thumb);
	} else {
		// else is there a previous page? if yes do the jump back and select last image of the list
		if ($('page' + current_page + '_head').previous('a[rel=page]')) {
			fetchGallery((current_page - 1), itemID, typeID, 0, true);
		}
	}

}

/*
 * function get_next_work()
 * get next work by invoking fetchGalleryDetails() function
 * 
 */

function get_next_work() {

	// verify if there is a next item	
	if ($('thumb' + current_thumb).up('li').next('li')) {
		next_thumb = $('thumb' + current_thumb).up('li').next('li').down('a').id.replace('thumb', '');
		// fetchGalleryDetails(next_thumb, typeID);
		SWFAddress.setValue('' + next_thumb);
	} else {
		// else is there a next page? if yes do the jump forward
		if ($('page' + current_page + '_head').next('a[rel=page]')) {
			fetchGallery((current_page + 1), itemID, typeID, 0, false);
		}
	}

}

/*
 * function calc_gmt_time()
 * function to calculate local time in GMT with offset
 * 
 */

function calc_gmt_time(offset) {

	var curDateTime = new Date();
  	var curHour = curDateTime.getHours() + curDateTime.getTimezoneOffset() / 60;
  	
  	curHour = curHour + offset;
  	
  	if (curHour >= 24) { curHour -= 24; }
  	if (curHour < 0) { curHour += 24; }
  	
  	// verify if we're in DST or not, and adjust hours
	if (isDST == 0) {
		curHour -= 1;
	}
  	
  	var curMin = curDateTime.getMinutes();
  	var curSec = curDateTime.getSeconds();
  	var curTime =  ((curHour < 10) ? "0" : "") + curHour + ":" + ((curMin < 10) ? "0" : "") + curMin + ":" + ((curSec < 10) ? "0" : "") + curSec;

	return curTime;

}

function echeck(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false;
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false;
	 }
	
	 if (str.indexOf(" ")!=-1){
		return false;
	 }

	 return true;				
}

/*
 * window onload event (dom loaded)
 * *****************************************************************************************
 * event.observe window load
 * based on prototype.js's event observe when dom is ready, scripts to be loaded onload
 *
 */

document.observe('dom:loaded', function() {
	
	// global calls
	//----------------------------------------------------------------------------------
	
	create_country_tip();	// country tooltip
	create_lang_tip();	// lang tooltip
	
	// section-specific onload scripting, loaded depending on sectionID
	
	// homepage
	//----------------------------------------------------------------------------------
	if (sectionID == 'home') {
	
		// tag event attach (nav over), not for clinique
		if (typeID != 'clinique') {
			attach_tag_event();
		}

		// add thumb switcher to artists
		$$('#home_list li a.home_list_link').each(function(preview) {	

			// assign fetch previews (including rotator) for each links on load
    			fetchPreviews(preview.rel, preview, 'load');
    			
    			// onmouseout, show back the first image
    			Event.observe(preview, 'mouseout', function(event) {

				// get image id
				image_id = $(preview).down('img').id;
    				
    				// show back first image
    				$(image_id).src = dw_Rotator.getInstanceById(image_id).imgs[0].src;
    				
    				// reset counter to 0
    				dw_Rotator.getInstanceById(image_id).ctr = 0;
    				
    			});

  		});
		
	}
	// details
	//----------------------------------------------------------------------------------
	if (sectionID == 'details') {
	
		// tag event attach (nav over), not for clinique
		if (typeID != 'clinique') {
			attach_tag_event();
		}
		
		// add tooltip for nav_artists
		attach_nav_previews();
		
		// start swfaddress watch
  		SWFAddress.onChange = function() {  

			// get new value, strip "/work" to keep thumb id only
			swfaddress_work = SWFAddress.getValue().replace("work", "");

			// fetch work with function, just make sure its not an empty swfaddress (on first load)
			if (swfaddress_work != "/" && swfaddress_work != "") {
				swfaddress_work = parseInt(swfaddress_work);
				fetchGalleryDetails(swfaddress_work, typeID);
			}
			
		}
		
		// var to keep track of current page and thumb
		current_page = '';
		current_thumb = '';
		
		// use SWFAddress to check if we need to load directly to a spcific work item, if not load first item
		SWFAddress.onInit = function() {
			var initWorkId = SWFAddress.getValue();
			//alert(initWorkId);
			initWorkId = initWorkId.replace("work", "");
			if (initWorkId != "/" && initWorkId != "") {
				workID = parseInt(initWorkId);
				//alert(workID);
			}
			
			// fetch gallery, first page if no workID set
			// if workID is set we'll handle the fetch properly in the PHP function
			fetchGallery(1, itemID, typeID, workID, false);
		}
			
		// for each page nav, observe click event and add ajax function
		$$('.details_browse_pages a').each(function(page) {
			Event.observe(page, 'click', function(event) {	
				fetchGallery(parseInt(page.innerHTML), itemID, typeID, 0, false);
			});
		});
		
		// attach click event to prev/next links
		Event.observe('browse_prev', 'click', function(event) { get_previous_work(); });
		Event.observe('browse_next', 'click', function(event) { get_next_work(); });
		
		// and to keyboard left and right arrow
		document.observe('keypress', function(event) { 
			if (Event.KEY_LEFT == event.keyCode) { get_previous_work(); event.stop(); }
			if (Event.KEY_RIGHT == event.keyCode) { get_next_work(); event.stop(); }
		});
	  		
	  	// add tooltip for similar (you may like), not for clinique
	  	if (typeID != 'clinique') {
		  	attach_similar_previews();
  		}
  		
	}
	// contact
	//----------------------------------------------------------------------------------
	if (sectionID == 'contact') {
	
		// add montreal local time, set a time to refresh each second
		$('current_time_mtl').update(calc_gmt_time(-4));
		new PeriodicalExecuter(function(pe) { $('current_time_mtl').update(calc_gmt_time(-4)) }, 1);
		
		// add london local time, set a time to refresh each second
		$('current_time_london').update(calc_gmt_time(1));
		new PeriodicalExecuter(function(pe) { $('current_time_london').update(calc_gmt_time(1)) }, 1);
		
		// add paris local time, set a time to refresh each second
		$('current_time_paris').update(calc_gmt_time(2));
		new PeriodicalExecuter(function(pe) { $('current_time_paris').update(calc_gmt_time(2)) }, 1);
		
	}
	// news
	//----------------------------------------------------------------------------------
	if (sectionID == 'news') {
	
		// add onchange event to artist dropdown select
		Event.observe('search_artist', 'change', function(event) { 
			window.location.href = $(this).value; 
		});
		
	}
	// pdf
	//----------------------------------------------------------------------------------
	if (sectionID == 'pdf') {
	
		// 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="" />');
			});
    		
  		});
		
	}
	// services
	//----------------------------------------------------------------------------------
	if (sectionID == 'services') {
	
		// attach toggle event to clinique_open, show div and close link, hide short desc
		$$('a.clinique_open').each(function(link) {
			Event.observe(link, 'click', function(event) {
				$(link).up('p').next('div').show();
				$(link).up('p').previous('h2').down('a.clinique_close').show();
				$(link).up('p').hide();
				Event.stop(event);
			});
		});
		
		// attach toggle event to clinique_close, show short desc, hide div and close link
		$$('a.clinique_close').each(function(link) {
			Event.observe(link, 'click', function(event) {
				$(link).up('h2').next('p').show();
				$(link).up('h2').next('div').hide();
				$(link).hide();
				Event.stop(event);
			});
		});
		
	}
	// tags
	//----------------------------------------------------------------------------------
	if (sectionID == 'tags') {
	
		// tag event attach (nav over)
		attach_tag_event();
		
	}
	 
});