// ===========
// = On Load =
// ===========
document.observe('dom:loaded', function() {
  // inserts the 'close' link into any flash messages that are displayed
  $$('.flash_close').each(function(message) {
    message.insert({
      bottom: "<div><a href='javascript:void(0)' onclick='$(this).up(\".flash\").remove()'>"+_('close message')+"</a></div>"
    })
  });
  
  // Toggle js/non_js visibility unless iPhone
  if (!navigator.userAgent.match(/iphone/i)) {
  	$$('.non_js').invoke('remove');
  	$$('.js').invoke('show');
  }

  // changes the shop navigation at the top right
  if ($('shop_links')) update_shop_nav();

  if (Prototype.Browser.Gecko) {
     // makes all the select boxes 6px wider unless they have a specified width.
     // this is done because firefox tends to chop of the right hand side of the options when the select is closed
    $$('select').each(function(e){
      if (e.getWidth() > 0) e.setStyle({width: e.getWidth()+6+"px"});
    });

    // Because firefox 2 doesn't support display:inline-block we have to add a span into the mix
    // to get the forms to display the labels correct, view notes at the end of this article:
    // http://www.alistapart.com/articles/prettyaccessibleforms
    $$('.smart_form label').each(function(label) {
      var hidden_ancestors = label.ancestors().select(function(e){return !e.visible();});
      if (hidden_ancestors || !label.visible()) {
        // if the label is not displayed we have to display it before we can get the width.
        // this may be a bug in prototype
        hidden_ancestors.invoke('show');
        var labelWidth = label.getWidth();
        hidden_ancestors.invoke('hide');
      } else {
        var labelWidth = label.getWidth();
      }
      var labelSpan           = document.createElement( 'span' );
      var labelContent        = label.innerHTML;
      labelSpan.style.display = 'block';
      labelSpan.style.width   = labelWidth+'px';
      labelSpan.innerHTML     = labelContent;
      label.style.display     = '-moz-inline-box';
      label.innerHTML         = null;
      label.appendChild( labelSpan );
    });
  }
});


function update_shop_nav() {
  var cart_count     = JSON.parse(unescape(Cookie.get("nav_cart")));
  var wishlist_count = JSON.parse(unescape(Cookie.get("nav_wishlist")));
  var logged_in      = JSON.parse(unescape(Cookie.get("nav_logged_in")));
  var user_id        = JSON.parse(unescape(Cookie.get("nav_user_id")));

  // insert the cart and wishlist counts
  insert_item_count($$('#shop_links #cart_link').first(), cart_count);
  insert_item_count($$('#shop_links #wishlist_link').first(), wishlist_count);
  if (logged_in) {
    // hide the login link
    $('login_link').hide();
  } else {
    // hide the account and logout links
    $('account_link').hide();
    $('logout_link').hide();
  }
}

function insert_item_count(el, count) {
  if (!parseInt(count) || parseInt(count) <= 0) return;
  text = count > 1 ? _("items") : _("item");
  el.insert({bottom: " <span class='small' style='color:#999'> " +count+ " " +text+ "</span>"});
}

// ============
// = On Click =
// ============
document.observe('click', function(e) {
  // if the region selector is visible and the user clicks out side the region select then fade the selector out
  if($('change_currency') && !e.element().up('#change_currency') && $('change_currency').visible()) {
    Effect.Fade('change_currency', {duration:0.2});
    Effect.Fade('change_currency_background', {duration:0.2});
  }
  if($('change_region') && !e.element().up('#change_region') && $('change_region').visible()) {
    Effect.Fade('change_region', {duration:0.2});
    Effect.Fade('change_region_background', {duration:0.2});
  }
});


// ===========
// = Helpers =
// ===========
function toggle_display(eid, bool) {
  $(eid).style.display = bool ? 'block' : 'none';
}

function toggle_disable(eid, bool) {
  $(eid).disabled = bool ? true : false;
}

function stripHTML(text){
  var re= /<\S[^><]*>/g
  return text.replace(re, "")
}

function nl2br(str, is_xhtml) {
  // http://kevin.vanzonneveld.net
  breakTag = '<br />';
  if (typeof is_xhtml != 'undefined' && !is_xhtml) {
    breakTag = '<br>';
  }

  return (str + '').replace(/([^>]?)\n/g, '$1'+ breakTag +'\n');
}

// =========================================
// = Internationalisation and Translations =
// =========================================
// WARNING: this function is duplicated in the pda.js file
function localized_path(path) {
  // return "/" +locale+ path; // locale is set in the template
  return "/" +currency+ path; // currency is set in the template
}

// Use _() to translate the string into the current language. eg: _('Thank you')
// This works by using the translation.js file that is included in the head of the page.
// If you need to do text replacement you can do somthing like _('Please choose a {{thing}}', 'size')
function _(key, value) {
  if (typeof(locale) == 'undefined' || typeof(I18n) == 'undefined' || !I18n[key]) {
    return insert_options(key, value);
  } else {
    var language = locale.substring(0,2);
    return insert_options(I18n[key][language] || key, _(value));
  }
}

function insert_options(key, value) {
  return value ? key.replace(/\{\{([^\}]+)\}\}/, _(value)) : key;
}

// converts a translation back to english from the currently selected locale
function _en(translation) {
  var english = "";
  $H(I18n).each(function(pair) {
    if (pair.value[locale] == translation) {
      english = pair.key;
      throw $break;
    }
  });
  if (english.length > 0) {
    return english;
  } else {
    return translation;
  }
}

// set this function as on onclick event to replace the element with a loading spinner
function show_spinner(eid) {
  if ($('loading_spinner')) {
    return;
  }
  $(eid).hide();
  // if the button has a parent with the class button_wrapper we have to hide that as well
  var wrapper = $(eid).up('.button_wrapper');
  var html = "<img src='/images/small_spinner.gif' id='loading_spinner'>";
  if (wrapper) {
    wrapper.hide();
    wrapper.insert({after: html})
  } else {
    $(eid).insert({after: html})
  }
}

function hide_spinner(eid) {
  $(eid).show();
  // if the button has a parent with the class button_wrapper we have to show that as well
  var wrapper = $(eid).up('.button_wrapper');
  if (wrapper) {
    wrapper.show();
  }
  $('loading_spinner').remove();
}

function checkMaxStringLength () {
  var success = true;
  $$('.centre_string').each(function(input){
    if(!checkLength(input, 10)) success = false;
  });
  return success;
}

function checkLength(input, max_inches) {
  var value   = parseFloat(input.value);
  input.value = isNaN(value) ? "" : value;
  var parent  = input.up('.customisations');
  // find checked input that has a name matching custom_length_units to determine if inches or cm has been checked
  var checked = parent.select('input([name*=custom_length_units])').select(function(e){return e.checked});
  if (checked.size() == 0) {
    // no length unit was selected to use the first one by default
    checked = parent.select('input([name*=custom_length_units])').first();
    checked.checked = true;
  } else {
    checked = checked.first();
  }

  // in  x  2.54 = cm
  if (checked.value == "in" && input.value > max_inches) {
    alert(_("One of the custom lengths you entered is too long."));
    input.value = max_inches;
    return false;
  }
  if (checked.value == "cm" && input.value > (max_inches * 2.54)) {
    alert(_("One of the custom lengths you entered is too long"));
    input.value = max_inches * 2.54;
    return false;
  }
  return true;
}

// Changes state form input to select/text based on country. Requires states.xjs
function update_state_input(country_code, state_input_eid, field_prefix, initial_state_id, initial_state_name) {
  // Removing previously reset state name/id
  if ($(state_input_eid+'_remove_other_state')) {
    $(state_input_eid+'_remove_other_state').remove();
  } 
  if ($H(country_states).keys().include(country_code)) {
    // Changing state input to select
    var html = '<select id="'+state_input_eid+'" name="'+field_prefix+'[state_id]">';
    html += '<option></option>';
    var state, selected;
    for (i=0; i < country_states[country_code].length; i++) {
      state = country_states[country_code][i];
      selected = (state['id'] == initial_state_id) ? ' selected' : '';
      html += '<option value="'+state['id']+'"'+selected+'>'+state['name']+'</option>\n';
    }
    html += '</select>';
    html += '<input type="hidden" name="'+field_prefix+'[state_name]" value="" id="'+state_input_eid+'_remove_other_state">';
    Element.replace(state_input_eid, html);
  } else {
    // Changing state input to text
    html = '<input id="'+state_input_eid+'" name="'+field_prefix+'[state_name]" value="'+initial_state_name+'">';
    html += '<input type="hidden" name="'+field_prefix+'[state_id]" value="" id="'+state_input_eid+'"_remove_other_state">';
    Element.replace(state_input_eid, html);
  }
}

function stop_all_links() {
  $$('a').each(function(link) {
    link.writeAttribute({ onclick: '' });
    link.writeAttribute({ href: 'javascript:void(0);' });
    link.observe('click', function(event) {
      event.stop();
    });
  });
}

function openPopup( strURL, intWidth, intHeight, blnNewWindow ) { //zubin
	var intScreenHeight = 0;
	//	get screen height
	if( parseInt( navigator.appVersion ) > 3 ) {
		intScreenHeight = screen.availHeight;
		if( !intScreenHeight ) {
			intScreenHeight = screen.height;
		}
	} else if(
		navigator.appName == "Netscape" && 
		parseInt( navigator.appVersion ) == 3 && 
		navigator.javaEnabled()
	) {
		var jToolkit = java.awt.Toolkit.getDefaultToolkit();
		var jScreenSize = jToolkit.getScreenSize();
		intScreenHeight = jScreenSize.height;
	} else {
		alert( 'Can\'t detect screen resolution' );
		return;
	}
	//	adjust dimensions if necessary
	if( intHeight > intScreenHeight ) {
		intHeight = intScreenHeight - 10;
	}
	if( blnNewWindow ) {
		//	new window
		var openPopup = window.open( strURL,'popup','toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=' + intWidth + ',height=' + intHeight );
		openPopup.focus();
	} else {
		//	same window
		window.resizeTo( intWidth, intHeight );
	}
	return;
}