// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

document.observe("dom:loaded", runOnDOMready);

var selection_box_open = false;
var multitag_box_slided = false;
var login_box_open = false;

function auth_token() {
	return AUTH_TOKEN;
}

function runOnDOMready() {
	
	// Connect to FireBug console for debugging, catch issues if is not found.
	try { console.log('init console... done'); } catch(e) { console = { log: function() {} } }

	//-------------------------------------------------------------
	// FLASH NOTICE
	//-------------------------------------------------------------
	// Close the flash notice
	if ($('flash-close')) {
		$('flash-close').observe('click', function(event) {
			slideNotices();
			Event.stop(event);
		});
	}	
	
	//-------------------------------------------------------------
	// SELECTIONS ( SAVE / RETRIEVE DRAWER )
	//-------------------------------------------------------------
	// Click on the login > slides down the drawer
	if ($('login-button')) {
		$('login-button').observe('click', function(event) {
			turn_selection_drawer(!selection_box_open);
			Event.stop(event);
		});
	}

	if ($('select_submit_button')) {
		$('select_submit_button').observe('click', function(event) {
			email_address = $('email_address').value;
			if (email_address == 'name@example.com' || !valid_email_address(email_address)) {
				event.stop();
				turn_selection_error(true);
			}
		});
	}

	// Click on the login > slides down the drawer
	if ($('login-button-sub')) {
		$('login-button-sub').observe('click', function(event) {
			turn_selection_drawer(!selection_box_open);
			Event.stop(event);
		});
	}
	
	// Click on the drawer Cancel button > slides up the drawer
	if ($('select_cancel_button')){
		$('select_cancel_button').observe('click', function(event) {
			turn_selection_drawer(false)
			Event.stop(event);
		});
	}

	// Focus / loose focus on the email address field > clears the field
	if ($('email_address')){
		$('email_address').observe('focus', function(event) {
			var element = event.element();
			if (element.value == 'name@example.com') {
				//element.value = '' ;
			}
			element.className = "focus";
		});
		$('email_address').observe('blur', function(event) {
			var element = event.element();
			if (element.value == '') {
				element.value = 'name@example.com' ;
				element.className = "";
			}
		});
	}

	//-------------------------------------------------------------
	//  SELECTION BUTTON ON THE PROJECT PAGE
	//-------------------------------------------------------------
	// Opens drawer on the selection page : login link
	if ($('selection-login')) {
		$('selection-login').observe('click', function(event) {
			if (!selection_box_open) { turn_selection_drawer(true); }
			window.scrollTo(0,0);
			Event.stop(event);
		});
	}

	//-------------------------------------------------------------
	// ADMIN LOGIN BOX
	//-------------------------------------------------------------
	if ($('lock-button')) {
		// Click on the lock > shows the login box
		$('lock-button').observe('click', function(event) {
			turn_login_box(!login_box_open)
			Event.stop(event);
		});

		// Click on the Cancel button > hides the login box
		$('login_cancel_button').observe('click', function(event) {
			turn_login_box(false)
			Event.stop(event);
		});

		// Focus on the username field > clears the field
		$('user_session_login').observe('focus', function(event) {
			var element = event.element();
			if (element.value == 'username') {
				//element.value = '' ;
			}
			element.className = "focus";
		});
		$('user_session_password').observe('focus', function(event) {
			var element = event.element();
			if (element.value == 'password') {
				element.value = '' ;
			}
			element.className = "focus";
		});
		// Loose Focus on the username field > put back "username"
		$('user_session_login').observe('blur', function(event) {
			var element = event.element();
			if (element.value == '') {
				element.value = 'username' ;
				element.className = "";
			} else {
				element.className = "focus";
			}
		});
		$('user_session_password').observe('blur', function(event) {
			var element = event.element();
			if (element.value == '') {
				element.value = 'password' ;
				element.className = "";
			} else {
				element.className = "focus";
			}
		});
	}

	//-------------------------------------------------------------
	// NEWSLETTER BOX ON HOMEPAGE
	//-------------------------------------------------------------
	if ($('tout-newsletter')) {

		// Focus on the email field > clears the field
		$('newsletter_email').observe('focus', function(event) {
			var element = event.element();
			element.className = "focus";
			if (element.value == 'name@example.com') {
				element.value = '' ;
			}
		});
		// Loose Focus on the email field > put back "name@example.com"
		$('newsletter_email').observe('blur', function(event) {
			var element = event.element();
			if (element.value == '') {
				element.value = 'name@example.com' ;
				element.className = "";
			} else {
				element.className = "focus";
			}
		});
		// Detecting on the fly if email address is valid
		$('newsletter_submit_button').observe('click', function(event) {
			email_address = $('newsletter_email').value;
			if (email_address == 'name@example.com' || !valid_email_address(email_address)) {
				event.stop();
				turn_newsletter_error(true);
			}
		});
		// Cleaning on cancel
		$('newsletter_cancel_button').observe('click', function(event) {
			event.stop();
			turn_newsletter_error(false);
		});
	}
	
	//-------------------------------------------------------------
	// PREVIOUS / NEXT BUTTONS
	//-------------------------------------------------------------
	// Previous Button hover reveals the label
	if ($('previous-label')) {
		$('previous-label').hide();
		$('previous-arrow').observe('mouseover', function(event) {
			$('previous-label').show();
		});
        $('previous-arrow').observe('mouseout', function(event) {
			$('previous-label').hide();
		});
	}

	// Next Button hover reveals the label
	if ($('next-label')) {
		$('next-label').hide();
		$('next-arrow').observe('mouseover', function(event) {
			$('next-label').show();
		});
        $('next-arrow').observe('mouseout', function(event) {
			$('next-label').hide();
		});
	}
	
	
	//-------------------------------------------------------------
	// PROJECT IMAGE HOVER
	//-------------------------------------------------------------
	// Image hover reveals the label
	if ($('project-image')) {
		$('image-hover').hide();
		$('project-image').observe('mouseover', function(event) {
			$('image-hover').appear({ duration:0.2 });
		});
		$('image-hover').observe('mouseover', function(event) {
			$('image-hover').show();
		});
        $('project-image').observe('mouseout', function(event) {
			$('image-hover').hide();
		});
	}

	//-------------------------------------------------------------
	// PROJECT MULTITAG CONTAINER => more tags
	//-------------------------------------------------------------
	if ($('more-button')) {
		$('more-label').update(more_less_labels[0]);
		$('more-button').observe('click', function(event) {
			if (multitag_box_slided) {
				$('multitags-spread').morph('left: 0em;',{duration:0.2});
				$('more-label').update(more_less_labels[0]);
			} else {
				$('multitags-spread').morph('left: -16.5em;',{duration:0.2});
				$('more-label').update(more_less_labels[1]);
			}
			multitag_box_slided = !multitag_box_slided;
			Event.stop(event);
		});
	}
	
	//-------------------------------------------------------------
	// PORTFOLIO IMAGE PAGINATION
	//-------------------------------------------------------------
	if ($('next-zone')) {
		$('next-zone').observe('mouseover', function(event) {
			$('next-button').appear({ duration:0.2 });
		});
		$('next-button').observe('mouseover', function(event) {
			$('next-button').show();
		});
        $('next-zone').observe('mouseout', function(event) {
			$('next-button').hide();
		});
        $('next-button').observe('mouseout', function(event) {
			$('next-button').hide();
		});
	}
	if ($('previous-zone')) {
		$('previous-zone').observe('mouseover', function(event) {
			$('previous-button').appear({ duration:0.2 });
		});
		$('previous-button').observe('mouseover', function(event) {
			$('previous-button').show();
		});
        $('previous-zone').observe('mouseout', function(event) {
			$('previous-button').hide();
		});
        $('previous-button').observe('mouseout', function(event) {
			$('previous-button').hide();
		});
	}
	
	//-------------------------------------------------------------
	// PORTFOLIO: OBSERVING KEYPRESS FOR PREVIOUS AND NEXT IMAGES
	//-------------------------------------------------------------

	// NEXT
	shortcut.add("Right",function() {
		if ($('next-button')) {
			$('next-button').appear({ duration:0.2, afterFinish: function() { window.location = next_url; } });
		} else if($('next-arrow')) {
			next_url = $('next-arrow').readAttribute('href');
			if (next_url){
				window.location = next_url;
				$('next-arrow').addClassName('flash');
			}
		}
	},{'disable_in_input':true});
	// PREVIOUS
	shortcut.add("Left",function() {
		if ($('previous-button')) {
			$('previous-button').appear({ duration:0.2, afterFinish: function() { window.location = previous_url; } });
		} else if($('previous-arrow')) {
			previous_url = $('previous-arrow').readAttribute('href');
			if (previous_url){
				window.location = previous_url;
				$('previous-arrow').addClassName('flash');
			}
		}
	},{'disable_in_input':true});
	// TOP
	shortcut.add("Up",function() {
		Effect.ScrollTo('header', { duration: 0.1 });
	},{'disable_in_input':true});
	
	//-------------------------------------------------------------
	// CONTACT PAGES
	//-------------------------------------------------------------
	// Click on the buttons show th big number
	$$('#maps a.phone_number_button').each(function(el, index) {
		el.observe('click', function(event) {
			$('number').update(phone_numbers[index]);
			$('huge-phone-number').appear({ duration:0.1 });
			Event.stop(event);
		});
	});
	// Click on the close hide the big number
	if ($('close-button')) {
		$('close-button').observe('click', function(event) {
			$('huge-phone-number').fade({ duration:0.3 });
			Event.stop(event);
		});
	}

	//-------------------------------------------------------------
	//  LISTING FILTER
	//-------------------------------------------------------------
	// Loop over each link inside the list and add the click method
	$$('.filter li a').each(function(el, index) {
		el.observe('click', function(event) {

			// This id will be sent to the Back end
			filter = el.up().identify();
      		currentChecked = el.up().hasClassName('checked');

			// Set the loading module
			$('loader').show();

      if (currentChecked) {
        filter = "all";
      }
      
			// Send an Ajax Update
			new Ajax.Request(ajax_url, {
				method: 'get',
				asynchronous: true,
				evalScripts: true,
				parameters: { toggle: filter, reset: 1 },
				onComplete: function() {
					$('loader').fade({ duration:0.2 });
				}
			});


      // clear current items
      $$('.filter li').each(function(el) { el.removeClassName('checked');})

			// set current item toggleCurrentClass(el.up());
      if (currentChecked) {
        el.up().removeClassName('checked');
      } else {
        el.up().addClassName('checked');
      }
			Event.stop(event);

			//$$('#filters-container.filter li.first').first().removeClassName('checked');
			
			// check to see if we have something checked
			// if not select the view all 

		if ($("filter-projects") != null) { 
			var checkedCount = $$('#filter-projects.filter li.checked').size();
			var extendedcheckedCount = $$('#extended-filter-projects.filter li.checked').size();
			if ((extendedcheckedCount + checkedCount) == 0) {
				$$('#filter-projects.filter li.first').first().addClassName('checked');
			}
		}

		if ($("filter-news") != null) { 
			var checkedCount = $$('#filter-news.filter li.checked').size();
			if (checkedCount == 0) {
				$$('#filter-news.filter li.first').first().addClassName('checked');
			}
		}

		if ($("toggle-button") != null) {
			on_flag = $('more-criteria-on');
			if (!extended_filter_open && extendedcheckedCount > 0) { on_flag.show() } else { on_flag.hide() }
		}
		
		});
	})

	// Add event to View All link. Removes all current classes and
	// adds current class to View All Link 
	$$('xxxx.filter li.first a').each(function(el) {
		el.observe('click', function(event) {
			clearCurrentItems(el);
			el.up().addClassName('checked');
			Event.stop(event);
		});
	})

	//-------------------------------------------------------------
	//  EXTENDED FILTER COLLAPSE / EXPAND
	//-------------------------------------------------------------
	if ($('toggle-button')) {
		$('toggle-button').observe('click', function(event) {
			on_flag = $('more-criteria-on');
			if (extended_filter_open) {
				$('toggle-button').className = '';
				$('extended-filter-container').hide();
				
				// check the selection count
	  		  elmore = $$('#toggle-button a').first();
	  			var extendedcheckedCount = $$('#extended-filter-projects.filter li.checked').size();
	  			if (extendedcheckedCount > 0)  { on_flag.show() } else { on_flag.hide() }
					if ($("toggle-button") != null) {
						on_flag = $('more-criteria-on');
						if (extendedcheckedCount > 0) { on_flag.show() } else { on_flag.hide() }
					}
			} else {
				$('toggle-button').className = 'expanded';
				$('extended-filter-container').show();
  			on_flag.hide();
			}
			extended_filter_open = !extended_filter_open;
			Event.stop(event);
		});
	}
	
	//-------------------------------------------------------------
	//  ATTACHMENT DRAWER
	//-------------------------------------------------------------
	if ($('attachment-button')) {
		$('attachment-button').observe('click', function(event) {
			if (attachment_drawer_open) {
				effect = Effect.SlideUp('attachment-drawer-container', { duration:0.2 } );
			} else {
				effect = Effect.SlideDown('attachment-drawer-container', { duration:0.2 } );
			}
			attachment_drawer_open = !attachment_drawer_open;
			Event.stop(event);
		});
	}

	if ($('clear-selection')) {
		$('clear-selection').observe('click', function(event) {
			var answer = confirm("Are you sure you want to clear you selection?")
			if (!answer) { Event.stop(event); }
		});
	}	

	//-------------------------------------------------------------
	//  SCROLL TO TOP OF PAGE
	//-------------------------------------------------------------
	if ($('back-to-top-button')) {
		$('back-to-top-button').observe('click', function(event) {
			Effect.ScrollTo('wrap', { duration: 0.1 });
			Event.stop(event);
		});
	}
	
	//-----------------------------------------------------------------------------
	//  CONTACT : ADDING A * TO THE PHONE LABEL WHEN THE PHONE METHOD IS SELECTED
	//-----------------------------------------------------------------------------
	if ($('contact_request_method')) {
		contact_method = $('contact_request_method').options[$('contact_request_method').selectedIndex].value;
		toggleStarOnPhoneLabel(contact_method=='phone');
		$('contact_request_method').observe('change', function(event) {
			contact_method = this.options[this.selectedIndex].value;
			toggleStarOnPhoneLabel(contact_method=='phone');
			Event.stop(event);
		});
	}
	
	// Render the red line (unless on IE)
	if (!is.ie) { createRedLine(); }
}

//******************************************************************************************************************
//   METHODS
//******************************************************************************************************************

function login_toggle_selection(id) {
	$('login_project').value = id;
	if (!selection_box_open) { turn_selection_drawer(true); }
	window.scrollTo(0,0);
}

function toggle_selection(add, id) {
	params = { authenticity_token: auth_token(), '_method': 'put' };
	if (add) {
		params.add_project = id;
	} else {
		params.remove_project = id;
	}
	// now use those two as params for the Ajax request.
	new Ajax.Request('/selection', {
		method: 'post',
		asynchronous: true,
		evalScripts: true,
		parameters: params
	});
}

function turn_selection_drawer(state) {
	selection_box_open = state;
	// this opens and closes the drawer
	if (state) {
		hideNotices();
		turn_selection_error(false);
		effect_1 = Effect.SlideDown('top-drawer', { duration:0.2,
			afterFinish: function(e){
				$('email_address').activate();
			} 
		});
	} else {
		effect_1 = Effect.SlideUp('top-drawer', { duration:0.2 } );
	}
	// this turns the selection button on / off
	$('login-button').className = ( (state) ? "on" : "" ) ;
}

function turn_selection_error(state) {
	if (state) {
		$('intro').hide();
		$('error-message').show();
	} else {
		$('intro').show();
		$('error-message').hide();
	}
}

function turn_newsletter_error(state) {
	if (state) {
		$('newsletter-intro').hide();
		$('newsletter-error-message').show();
		$('newsletter_cancel_button').show();
	} else {
		$('newsletter-intro').show();
		$('newsletter-error-message').hide();
		$('newsletter_cancel_button').hide();
	}
}

function turn_login_box(state) {
	login_box_open = state;
	// this opens and closes the drawer
	if (state) {
		$('login-box-container').show();
		// Effect.ScrollTo('login-box-container', { duration: 0.1, offset: 0 });
		$('user_session_login').activate();
	} else {
		$('login-box-container').hide();
	}
	// this turns the selection button on / off
	$('lock-button').className = ( (state) ? "on" : "" ) ;
}

// Simple toggle function. This adds or removes the 
// current class depending on which it already has
function toggleCurrentClass(el) {
	if(el.hasClassName('checked')) {
		el.removeClassName('checked');
	} else {
		el.addClassName('checked');
	}
}

// Removes the current class from all list items
function clearCurrentItems(el) {
	el.up().up().childElements().each(function(el) { el.removeClassName('checked');})
}

// Hides the flash notice when showing the login drawer
function hideNotices() {
	if ($('flash-notice')) {
		$('flash-notice').hide();
	}
}

// Hides by sliding the flash notices
function slideNotices() {
	effect_1 = Effect.SlideUp('flash-notice', { duration:0.2 } );
}

// Adds / removes the * to the phone number on the contact form
function toggleStarOnPhoneLabel(state) {
	text = $('contact-request-phone-label').innerHTML.gsub(/\s\*/, '');

	if (state) {
		$('contact-request-phone-label').update(text + " *");
	} else {
		$('contact-request-phone-label').update(text);
	}
}

// Function to validates the email address for the selection drawer
function valid_email_address(address) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(address) == false) {
     return false;
   } else {
     return true;
   }
}

var createRedLine = function()
{
	var i = 969, container = document.createDocumentFragment();
	while(i--)
	{
		var pixel = document.createElement('div');
		pixel.className = 'pixel';
		pixel.style.left = (968-i)+"px";
		pixel.style.top = i+"px";
		container.appendChild(pixel);
	}
	$('red-line').appendChild(container);
}