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

//////////////////////////////////////////////////////////////////////////////
// show/hide about submenu

var about_submenu_visible = false;

function about_submenu_toggle() {
  if(about_submenu_visible) {
    $('about_submenu') .hide();
    about_submenu_visible = false;
  } else {
    $('about_submenu').show();
    about_submenu_visible = true;
  }
}

//////////////////////////////////////////////////////////////////////////////
// ie6 make transparent
var el_fnFixPng = function(img) {
  var src = img.src;
  img.style.width = img.width + "px";
  img.style.height = img.height + "px";
  img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "', sizingMethod='scale')";
  img.src = '/x.gif';
}; 


function update_email_friend_body_field(receiver_name, sender_name, path) {
  var el = $('email_friend_body');
  var text = "Hi " + receiver_name + ",\n\
\n\
Check this out! I was visiting Larger Than Life prints (www.LTLprints.com) and found this image I thought you might like. Click <a href='http://www.ltlprints.com" + path + "'>here</a> to view the image. They use a unique removable fabric to print all of their BIG WALL GRAPHICS. The material will stick to almost anything and it's repositionable! You can peel it down and move it around over and over again.\n\
\n\
Thanks,\n\
" + sender_name;
  if(Prototype.Browser.IE) {el.innerText = text;} else {el.innerHTML = 
text;}
}

function select_states(country, field_prefix) {
  if((country != 'US') && (country != 'CA') && (country != 'AU')) {
    $(field_prefix + '_state').disable();
  } else {    
    $(field_prefix + '_state').enable();
  }
}

function add_to_design_tool(id, partner_name) {
  var selected_size = null;
  
  if(partner_name == undefined) {
  	partner_name = 'images';
  }
  
  $$('#instantly_add_to_cart table tr td input').each(function(el){
     if(el.checked)
       selected_size = el.value;       
  });

  if(selected_size == null) {
    alert('You must select size of the print!');
    return false;
  } else {
    location.href='/' + partner_name + '/design_tool/' + id + '?print_size=' + selected_size;
  }
}

function is_print_size_selected_on_permalink() {
  var selected = false;
  $$('#instantly_add_to_cart table tr td input').each(function(el) { 
    if(el.checked)
      selected = true;
  });
  return selected;
}

var colorEl;
var colorP;
window.bg_color = 'FF5500'; 

// additional function
function getElementPosition(elemId)
{
  var elem = $(elemId);

  var w = elem.offsetWidth;
  var h = elem.offsetHeight;

  var l = 0;
  var t = 0;

  while (elem) {
    l += elem.offsetLeft;
    t += elem.offsetTop;
    elem = elem.offsetParent;
  }

  return {"left":l, "top":t, "width": w, "height":h};
}

var buildColorPicker = function(id) {
  colorEl = id;
  pos = getElementPosition(id);
  $('cpDiv').style.top = pos.top+'px';
  $('cpDiv').style.left = pos.left+'px';
  $('cpDiv').style.display = 'block';

  if (colorP) {
    window.frames['cpFrame'].setPicker($F(id+'_hex'));
  } else {
    window.frames['cpFrame'].loadPicker($F(id+'_hex'));
    colorP = true;
  }
};
 
var hideColorPicker = function () {
  new Effect.Fade($('cpDiv'), {duration: 0.5});
};

var setColor = function() {
  id = colorEl;
  color = window.frames['cpFrame'].document.getElementById('cp1_Hex').value;
  $(id+'_hex').value = color;
  $(id+'_fill').style.backgroundColor = '#'+color;
  hideColorPicker();
  
  window.bg_color = color;
};

/* catalog javascript */ 
function set_events_on_catalog_images() {

  var preloaded_images = {};

  $$('.catagoryImage a div.zoom_in img').each(function(img){
    var image = new Image;  
    image.src = img.src.split('_thumb')[0] + '_bthumb.png';
    preloaded_images[img.src] = image;
  });

  $$('.catagoryImage a div.zoom_in img').each(function(el){  	
    Event.observe(el, 'mouseover', function(e){    	      	 
      Event.stop(e);
	  
      window.original_path = this.src;

      window.w = $(this).getWidth();
      window.h = $(this).getHeight();
	  
      window.original_h = window.h;
      window.original_w = window.w;
	  
      window.el_offset = $(this).cumulativeOffset();
      el.src = preloaded_images[this.src].src;
	  
      if(window.original_w >  window.original_h) {
        while(window.w < 350) {
          window.w += 40;
		  window.h += 40;
		  if(el.style.marginLeft == '') el.style.marginLeft = '0px';
 		  if(el.style.marginTop == '') el.style.marginTop = '0px';
          el.style.marginLeft = (parseInt(el.style.marginLeft) - 20) + 'px';
          el.style.marginTop  = (parseInt(el.style.marginTop)  - 20) + 'px';
          el.style.width = window.w + 'px';      
          el.style.height = window.h + 'px';      
        }    
      } else {
        while(window.h < 350) {
          window.h += 40;
		  window.w += 40;
  		  if(el.style.marginLeft == '') el.style.marginLeft = '0px';
 		  if(el.style.marginTop == '') el.style.marginTop = '0px';
          el.style.marginLeft = (parseInt(el.style.marginLeft) - 20) + 'px';
          el.style.marginTop  = (parseInt(el.style.marginTop)  - 20) + 'px';
          el.style.height = window.h + 'px';      
		  el.style.width  = window.w + 'px';      
        }    
      } 
	      	    
    });
	
    Event.observe(el, 'mousemove', function(ev){            	  
      if(window.el_offset[0]==undefined || window.el_offset[1] == undefined)
	return;
	
      Event.stop(ev);
		
      var off_x = window.el_offset[0];
      var off_y = window.el_offset[1];
		  
      if(Prototype.Browser.IE) {		 		
	var ev_x = ev.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	var ev_y = ev.clientY + document.body.scrollTop + document.documentElement.scrollTop;
			
        var x = parseInt(ev_x) - off_x;
	var y = parseInt(ev_y) - off_y;
      } else {
        var x = parseInt(ev.pageX) - off_x;
	var y = parseInt(ev.pageY) - off_y;
      }
		
      var x_tmp = parseInt(Math.abs(x) * 1.73).toString();
      var y_tmp = parseInt(Math.abs(y) * 1.73).toString();
      el.style.marginLeft = '-' + x_tmp + 'px';
      el.style.marginTop  = '-' + y_tmp + 'px';        
    });
	  
    Event.observe(el, 'mouseout', function(e){	
      Event.stop(e);
	        
      el.src = window.original_path;

      el.style.width  = window.original_w + 'px';    
      el.style.height = window.original_h + 'px';
     
      el.style.marginTop = '0px';
      el.style.marginLeft = '0px';
    
      window.h = 134;
      window.w = 134;
      window.original_h = null;
      window.original_w = null;
    
      window.el_offset = [];      
    });	
  });
}

function tie_enter_to_login(form_id) {
  if($(form_id)) {
    document.onkeypress = function(e) {
	  e = (e && e!=undefined) ? e : ((window.event) ? window.event : null);
  	  if(e.keyCode == 13) {
	    $(form_id).submit();
	  }
	}
  }
}

window.chars_for_instructions_left = 240;

function setup_verbal_instructions_watcher() {
  $('instructions').onkeyup = function(e) {
  	e = (window.event ? window.event : e);
	$('chars_left').innerHTML = 240 - $('instructions').value.length;
	if(parseInt($('chars_left').innerHTML) < 0) {
	  $('chars_left').style.color = 'red';
	} else {
	  $('chars_left').style.color = '#000';
	}
  }
}

function untie_enter_from_login() {
  document.onkeypress = function(){}
}

document.observe("dom:loaded", function() {
  if($('header_search_field')) {
    $('header_search_field').onkeypress = function(e) {
  	  e = (window.event ? window.event : e);
	  if(e.keyCode == 13) { // Enter
	    $('header_search_form').submit();	  
	  }
    };
  }
  
  if($('search_key')) {
    $('search_key').onkeypress = function(e) {
      e = (window.event ? window.event : e);
	  if(e.keyCode == 13) { // Enter
	    $('catalog_search_form').submit();
	  }
    };
  }
	
  var flash = $('notice') || $('error');
  if(flash && (!flash.hasClassName('stay_on_top'))) {
    new Effect.Highlight(flash, { queue: { position: 'front', scope: 'menuxscope' } });
    new Effect.Fade(flash, { queue: { position: 'end', scope: 'menuxscope' } })
  }
});

function show_signup_dialog(url) {
  if(typeof(url)=='undefined') url = '/images/user_auth';
  
  new Ajax.Updater('hidden_content_user_auth_shop', url,
    {asynchronous:true,
	 evalScripts:true,
	 requestHeaders: ['Accept', 'text/html, application/xml, text/xml, */*'],
	 onComplete:function(request){
	   RedBox.addHiddenContent('hidden_content_user_auth_shop'); 
	 }, 
	 onLoading:function(request){RedBox.loading();} 
  });
}

function show_where_would_you_like_to_go() {
  new Ajax.Updater('hidden_content_where_would_you', '/shop/what_would_you',
    {asynchronous:true,
	 evalScripts:true,
	 requestHeaders: ['Accept', 'text/html, application/xml, text/xml, */*'],
	 onComplete:function(request){
	   RedBox.addHiddenContent('hidden_content_where_would_you'); 
	 }, 
	 onLoading:function(request){RedBox.loading();} 
  });
}
				
function stopDefaults(e) {
	if(e && e.preventDefault)
	  e.preventDefault();
	else
	  window.event.returnValue = false;
	  
	return false;
}

function add_email_validation() {
	$('registration_of_new_user').onsubmit = function(event) {
	  if($('new_user_password').value == '') {
	  	 $('login_errors').update('<li>You must fill in the password field!</li>');
		 $('login_errors').show();
		 return stopDefaults(event);
	  }
	  
	  var url = '/shop/check_email_uniqueness?email=' + encodeURIComponent($('new_user_email').value);
	  
      new Ajax.Request(url, {
        method: 'get',
		asynchronous: false,
        onSuccess: function(response) {
	      if(response.responseText=='true') {
		  	$('login_errors').update('');
		  	$('login_errors').hide();
			return true;
	      } else {
   	        $('login_errors').update('<li>The email you have entered is not unique. Try another one!</li>');
		    $('login_errors').show();
			return stopDefaults(event);
	      }
        }
      });
	}
};

function ajax_user_registration(redirect_to) {	
	$('returning_user').onsubmit = function(event) {
	  if($('returning_user_password').value == '') {
	  	 $('login_errors').update('<li>You must fill in the password field!</li>');
		 $('login_errors').show();
		 return stopDefaults(event);
	  }

    new Ajax.Request($('returning_user').action, {
        method: 'post',
		asynchronous: false,
		parameters: {'login': encodeURIComponent($('returning_user_email').value), 'password': encodeURIComponent($('returning_user_password').value)},
        onSuccess: function(response) {
	      if(response.responseText=='false') {
   	        $('login_errors').update('<li>The email and password you have entered are invalid. Try another ones!</li>');
		    $('login_errors').show();
			return stopDefaults(event);
	      } else {
		  	$('login_errors').update('');
		  	$('login_errors').hide();
			location.href = redirect_to;
    		return stopDefaults(event);
	      }
        }
      });
	}
};

function innerfade(id, period, duration){
	var index = 0;
  $(id).childElements().each(function(i){ 	  
	  if(index!=0) 
	    i.hide();	  
    index++;
	});
	
  new PeriodicalExecuter(function(pe) {
    var els = getNextInnerfadeEl(id);	  
    //new Effect.Fade(els[0], { duration: duration*0.1, queue: { position: 'front', scope: 'menuxscope' } });
    $(els[0]).hide();//.style.display = 'none';
    $(els[1]).show();//.style.display = 'visible';
	  //new Effect.Appear(els[1], { duration: duration*0.1, queue: { position: 'end', scope: 'menuxscope' } });	  
  }, period);
}

function getNextInnerfadeEl(parent){
  var next = false;
  var ret = new Array();
  
  var els = $(parent).childElements();
  
  els.each(function(i){ 
    if(ret.length==1 && next) {
	  ret.push(i);
	}
    if(ret.length==0 && i.style.display != 'none') {
	  ret.push(i);
      next = true;
	}
  });
  
  if(ret.length==0){
  	ret.push(els[0], els[1]);
  } else if (ret.length==1) {
  	ret.push(els[0]);
  }
  return ret;
}

function emptyField(){
    document.getElementById("account_address_address").value = '';
    document.getElementById("account_address_apartment").value = '';
    document.getElementById("account_address_city").value = '';
    document.getElementById("account_address_state").value = '';
    document.getElementById("account_address_country").value = '';
    document.getElementById("account_address_zip").value = '';
    document.getElementById("account_address_phone").value = '';
    document.getElementById("account_address_address_label").value = '';
}
	
function showSubCategory(id){
    $('subcategories').show();
    new Ajax.Updater('subcategories','/sell/show_subcategories/'+id, {asynchronous:true, evalScripts:true}); return false;
}
	
function addTax(id, action){
    if(action == 'index'){
        new Ajax.Updater('amounts', '/checkout/add_tax/'+id, {asynchronous:true, evalScripts:true}); return false;
    }
}

// these 3 functions are used only on permalink pages
function copyToClipboard(field) {
  var content = eval("document."+field);
  content.focus();
  content.select();
  range = content.createTextRange();
  range.execCommand("Copy");
  window.status="Contents copied to clipboard";
  setTimeout("window.status=''",1800);
}
function clickclear(thisfield, defaulttext) {
  if (thisfield.value == defaulttext) { thisfield.value = "";}
}
function clickrecall(thisfield, defaulttext) {
  if (thisfield.value == "") { thisfield.value = defaulttext; }
}
