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

function push(a, v) {
    a[a.length] = v;
}

function toggle_div(id) {
    var el = $(id);
    if (el) {
	if (el.visible()) {
	    el.hide();
	}
	else {
	    el.show();
	}
    }
}

/// form_section_toggle stuff.
/// Page must call form_section_toggle_init() helper in application_helpers.
function form_section_toggle_add_div(section, divID) {
    if (!_form_section_toggle[section]) {
	_form_section_toggle[section] = [];
    }
    push(_form_section_toggle[section], divID);
}
function form_section_toggle_show_div(section, divID) {
    var a = _form_section_toggle[section];
    for (var i = 0; i < a.length; ++i) {
	if (a[i] != divID) {
	    $(a[i]).hide();
	}
    }
    $(divID).show();
}


function copy_input_to_hidden(input_id, hidden_id) {
    var iel = $(input_id);
    var hel = $(hidden_id);
    if (iel && hel) {
	hel.value = iel.value;
    }
}

function do_spinners_on_all_page_ajax(show_fn, hide_fn) {
    var hide = function() {
	if (hide_fn)
	    (hide_fn)();
	else if ($('spinner'))
	    $('spinner').hide();
    };
    Ajax.Responders.register({
	onCreate:   function() {
	    if (show_fn)
		(show_fn)();
	    else if ($('spinner'))
		$('spinner').show();
	},
	onComplete: hide,
	onException: hide
    });
}


function portfolio_item_resize_after_load(mv) {
    window.setTimeout(function() {
	var els = $(mv.content).select('div#portfolio_image');
	var w = $(els[0]).getWidth();
	var h = $(els[0]).getHeight();
	if (w < 10)
	    w = 290;
	if (h < 10)
	    h = 250;
	mv.sizeToContent(w + 20, h + 125);
	mv.showCentered();
    }, 10);
}


function stylist_service_areas_force_preferred() {
    var ph = $('preferred_hood_select');
    if (ph) {
	var v = ph.options[ph.selectedIndex].value;
	if (v && $(v))
	    $(v).checked = true;
    }
}

function output_index_flash() {
    document.write('<embed id="testimonials" src="/testimonials.swf" width="282" height="178" allowscriptaccess="always" allowfullscreen="false" />');
}

function add_option_to_select(id, name, value) {
    var el = $(id);
    if (!el)
	return;
    var o = null;
    el.select('option').each(function(opt) {
	if (opt.value == value)
	    o = opt;
    });
    if (!o) {
	o = document.createElement('option');
	o.value = value;
	o.innerHTML = name;
	el.appendChild(o);
    }
}

function remove_option_from_select(id, value) {
    var el = $(id);
    if (!el)
	return;
    var o = null;
    el.select('option').each(function(opt) {
	if (opt.value == value)
	    $(opt).remove();
    });
}


// Featured stylists.

var _fs = {};
var slideShowParams = {}, categoryCount = 0, currentLap = 0;
function fs_init() {
    _fs.data = _fs_data;
    if (!(_fs.data && _fs.data.length > 0)) {
			_fs = null;
			return;
    }
    _fs.intializing = true;
    _fs.controlsEl = $('featured_work_controls');
    _fs.categoryEl = $('service-list');
		_fs.stylistPriceRemarkEl = $('stylist-price_remark');
    _fs.stylistNameEl = $('stylist-name');
    _fs.stylistLinkEl = $('stylist-link');
    _fs.photoEl = $('featured_work');
    _fs.spinnerEl = $('featured_work_spinner');
    _fs.navButtons = $('navigation-buttons');
    _fs.prevStylistLink = $('prev-stylist');
    _fs.nextStylistLink = $('next-stylist');
		_fs.stylistHighestCount = 0;
    if (!(_fs.controlsEl && _fs.categoryEl && _fs.stylistPriceRemarkEl && _fs.stylistNameEl && _fs.stylistLinkEl && _fs.photoEl && _fs.spinnerEl && _fs.prevStylistLink && _fs.nextStylistLink)) {
	_fs = null;
	return;
    }

    for (var i = 0; i < _fs.data.length; ++i) {
			var category = _fs.data[i];
			if (!(category['name'] && category['stylists'] && category['stylists'].length > 0)) {
	    	_fs = null;
	    	return;
			}
			
			_fs.stylistHighestCount = Math.max(_fs.stylistHighestCount, category.stylists.length);
			
			for (var j = 0; j < category.stylists.length; ++j) {
	    	var stylist = category.stylists[j];
	    	if (!(stylist['name'] && stylist['profile_url'] && stylist['photo_url'])) {
					_fs = null;
					return;
	    	}
	    	stylist.photo_obj = new Image();
	    	stylist.photo_obj.isLoaded = false;
	    	stylist.photo_obj._onloads = [(function() {
					var obj = stylist.photo_obj;
					return function() {
		    		obj.isLoaded = true;
		    		if (_fs.spinnerTimeout) {
							window.clearTimeout(_fs.spinnerTimeout);
							_fs.spinnerTimeout = null;
		    		}
		    		$(_fs.photoEl.parentNode).show();
		    		_fs.spinnerEl.hide();
        		_fs.navButtons.show();
					};
	    })()];
	    stylist.photo_obj.addOnLoad = (function() {
				var obj = stylist.photo_obj;
				return function(fn) {
		    	obj._onloads.push(fn);
				};
	    })();
	    stylist.photo_obj.onload = (function() {
				var obj = stylist.photo_obj;
				return function(fn) {
		    	obj._onloads.each(function(fn) {
						fn();
		    	});
				};
	    })();
	    stylist.photo_obj.load = (function() {
				var obj = stylist.photo_obj;
				var url = stylist.photo_url;
				return function() {
		    	if (!obj.isLoaded) {
						obj.src = url;
		    	}
				};
	    })();
		}
		if (i < 1 && category.stylists.length > 0) {
	    category.stylists[0].photo_obj.load();
		}

		var opt = document.createElement('option');
		opt.value = i;
	opt.innerHTML = category.name;
	_fs.categoryEl.appendChild(opt);
    }

    _fs.setStylist = function(i) {
	if (!_fs.currentCategory) {
	    return;
	}
	_fs.currentStylist = i;
	var stylist = _fs.currentCategory.stylists[_fs.currentStylist];
	_fs.stylistPriceRemarkEl.update(stylist.price_remark);
	_fs.stylistNameEl.update(stylist.name);
	_fs.stylistLinkEl.href = stylist.profile_url + "?via=stylony";
	var update_link = function() {
	    if (_fs.photoEl.parentNode.tagName == 'a' || _fs.photoEl.parentNode.tagName == 'A') {
				_fs.photoEl.parentNode.href = stylist.profile_url + "?via=stylony";
	    }
	    else {
				var el = document.createElement('a');
				var parent = _fs.photoEl.parentNode;
				parent.removeChild(_fs.photoEl);
				el.appendChild(_fs.photoEl);
				parent.appendChild(el);
				el.href = stylist.profile_url + "?via=stylony";
	    }
	};
	if (stylist.photo_obj.isLoaded || _fs.intializing) {
	    _fs.photoEl.show();
	    _fs.spinnerEl.hide();
      _fs.navButtons.show();
	    _fs.photoEl.src = stylist.photo_url;
	    update_link();
	}
	else {
	    _fs.spinnerTimeout = window.setTimeout(function() {
		$(_fs.photoEl.parentNode).hide();
    _fs.navButtons.hide();
		_fs.spinnerEl.show();
	    }, 200);
//	    window.setTimeout(function() {
	    stylist.photo_obj.addOnLoad(update_link);
	    stylist.photo_obj.load();
	    _fs.photoEl.src = stylist.photo_url;
//	    }, 1000);
	}
    }

    _fs.prevStylistLink.observe('click', function(event) {
			if (_fs.currentStylist != null) {
				if (_fs.currentStylist <= 0) {
					_fs.setStylist(_fs.currentCategory.stylists.length - 1);
				}
				else {
					_fs.setStylist(_fs.currentStylist - 1);
				}
			}
			event.stop();
    });
		
    _fs.nextStylistLink.observe('click', function(event) {
			if (_fs.currentStylist != null) {
				if (_fs.currentStylist == _fs.currentCategory.stylists.length - 1) {
					_fs.setStylist(0);
				}
				else {
					_fs.setStylist(_fs.currentStylist + 1);
				}
			}
			event.stop();
    });

    _fs.setCategory = function(i) {
			if (!(i >= 0 && i < _fs.data.length)) {
					return;
			}
			_fs.currentCategory = _fs.data[i];
			_fs.setStylist(0);
    }
    _fs.categoryEl.observe('change', (function() {
			_fs.setCategory(this.selectedIndex);
    }).bindAsEventListener(_fs.categoryEl));

    _fs.photoEl.hide();
    _fs.setCategory(0);
    _fs.controlsEl.show();
    _fs.intializing = false;		
		slideShow();	
}

function slideShow(){
	slideShowParams.xIndex = 0;
	slideShowParams.running = true;
	if(_fs.currentStylist != null){
		slideShowParams.currentStylist = _fs.currentStylist;
	}		
	categoryCount = (_fs.data == null)? 0 : _fs.data.length;	
	// Initial call to slide show starts after 5 secs when the page completed loading...
	slideShowParams.timeOut = setTimeout("changeSlideContent()", 5000);
}	

function changeSlideContent(){
	if(slideShowParams.running)
	{
		// Timing value changed from 6 secs(6000) to 10 secs(10000)
		slideShowParams.waitingTime = 10000;
		slideShowParams.xIndex += 1;						
		currentLap = (currentLap >= _fs.stylistHighestCount)? 0 : currentLap;	
		if(slideShowParams.xIndex < categoryCount)
		{		
			_fs.categoryEl.selectedIndex = slideShowParams.xIndex;
			_fs.currentCategory = _fs.data[slideShowParams.xIndex];			
			if(_fs.data[slideShowParams.xIndex].stylists[currentLap] != null)	{							
				_fs.setStylist(currentLap);				
			}
			else
			{
				// Display first image of the category. Because the appropriate image is not available for this.
				_fs.setStylist(0);				
			}
		}
		else
		{			
			slideShowParams.xIndex = 0;		// again starts from first category
			currentLap += 1;		
			_fs.categoryEl.selectedIndex = slideShowParams.xIndex;
			_fs.currentCategory = _fs.data[slideShowParams.xIndex];
			if(_fs.data[slideShowParams.xIndex].stylists[currentLap] != null)	{							
				_fs.setStylist(currentLap);				
			}
			else
			{
				// Display first image of the category. Because the appropriate image is not available for this.
				_fs.setStylist(0);				
			}
		}	
		$(_fs.photoEl.parentNode).show();
	}
	else
	{
		// Slide show is stopped now. At the execution time user will mouse over the appropriate div.
		// Starts again when the cursor moved out from the appropriate div.
		// Reset all the setting values inturn it returns to initial stage of execution.
		slideShowParams.xIndex = 0;
		currentLap = 0;
	}
	
	slideShowParams.timeOut = setTimeout("changeSlideContent()", slideShowParams.waitingTime);
}

function stopSlideShowEvent()
{
	slideShowParams.running = false;
}

function startSlideShowEvent()
{
	slideShowParams.running = true;
}

/// Select services page.

function _get_service_els() {
    var els = [];
    $('services_selected').select('li.option').each(function(el) {
	if (el.id != 'selection_template' && el.id != 'services_hint' && !el.hasClassName('service_heading')) {
	    els.push(el);
	}
    });
    return els;
}

function _services_changed() {
    var count = _get_service_els().length;
    if (count < 1) {
	$('services_hint').show();
	$('services_submit').hide();
    }
    else {
	$('services_hint').hide();
	$('services_submit').show();
    }
    if (count >= 5) {
	$('services_limit_note').show();
	$('services_select_more_note').hide();
    }
    else {
	$('services_limit_note').hide();
	if (count > 0) {
	    $('services_select_more_note').show();
	}
	else {
	    $('services_select_more_note').hide();
	}
    }
}

function services_init() {
    _get_service_els().each(function(el) {
	var a_el = el.select('a')[0];
	a_el.observe('click', function(event) {
	    el.remove();
	    _services_changed();
	    event.stop();
	});
    });
    _services_changed();
}

function services_select(id, text) {
    if (_get_service_els().length >= 5) {
	return;
    }

    var new_el = $('selection_template').cloneNode(true);
    new_el.id = null;

    var a_el = new_el.select('a')[0];
    a_el.update(text);
    a_el.observe('click', function(event) {
	new_el.remove();
	_services_changed();
	event.stop();
    });

    var h_el = new_el.select('input')[0];
    h_el.value = id;

    $('services_selected').appendChild(new_el);
    new_el.show();

    _services_changed();
}


// Stylist registration.
function update_booking_link_preview() {
    var url = $('booking_link_preview_url');
    var error = $('booking_link_preview_error');
    var field = $('username_field');

    var name = field.value;
    if (name) {
	name.replace(/[^\w\d\-]/g, '');
    }

    if (!name || name == '') {
	url.hide();
	error.show();
	error.update('Please enter a username.<br/>Your username is used to create your booking URL.');
    }
    else if (!name.match(/^[a-zA-Z][\w\d\-]*$/)) {
	url.hide();
	error.show();
	error.update('Your username may contain only<br/>letters, numbers and underscores or dashes,<br/>and must start with a letter.');
    }
    else if (name.length < 5) {
	url.hide();
	error.show();
	error.update('Your username must be at least 5 characters long.');
    }
    else {
	url.show();
	error.hide();
	url.update('http://www.stylony.com/' + name);
    }
}


function duration_picker_update_hidden(id) {
    var h = $('duration_picker_hours_' + id);
    var m = $('duration_picker_minutes_' + id);
    var f = $('duration_picker_field_' + id);
    if (h && m && f) {
	f.value = parseInt(h.value)*60 + parseInt(m.value);
    }
}


function displayFlashMessage(description, url) {
	if($('flash_notice') == null)
	{
		Element.insert("contents", { top: "<div id='flash_notice' class='notice'><a class='link_feel_colour' href='" + url + "'>" +description+ "</a> deleted successfully.</div>" });
	}
	else
	{
		$('flash_notice').innerHTML = "<a class='link_feel_colour' href='" + url + "'>" +description+ "</a> deleted successfully.";
	}	
}

function popup_window(url, description)
{
	var window_width = 800;
	var window_height = 400;
	var left_position = (document.width - window_width) / 2;
	var top_position = 200;
	window.open(url, "mywindow", 'width='+ window_width +', height=' + window_height + ', left=' + left_position +', top=' + top_position + ', scrollbars=yes'); 
	return false;
}


function removeServiceFilterOptionsIfCategory(category_id)
{
  var slectbox = $('service')
  var options = selectbox.options
  var i;
  for(i=options.length-1;i>=0;i--)
  {
    if(options[i].readAttribute('service_category_id')==category_id){selectbox.remove(i)}
  }
}