var DocLoaded = false;
var popupwin;
var PreviewWin;
var CurrentSL = "";
var winFldr;

// ###################
// SITE-WIDE ON-LOAD BEHAVIOURS


  //Break out of any parent frame:
  if (self != top) top.location.href = self.location.href;

  // On DOM loaded:
	document.observe("dom:loaded", function() {  
	  
	  $$('.drop-shadow').each(function(e){ dropShadow(e);});
		initBasketViewer();
	  regularize_panel_heights();
    observe_scrollers();

		if ($('header')) {
			$('header').setStyle({ 'cursor':'pointer'});
			$('header').observe('click', function(event){
				if (Event.element(event).id=='header' || Event.element(event).id=='headerInfo' || Event.element(event).hasClassName('logo_wrapper') ){
					window.location.href = '/';
				}
			}); 
		}
		
	});
	
	// On window complete:
	//Event.observe(window, 'load', function(){});


// ###################
function redirect_from_popup_to_sign_in(){
  target = opener ? opener : self;
	target.location.href = target.location.href
													+ (target.location.href.indexOf('?') > -1 ? '&' : '?') 
													+ "redirect_popup_to_sign_in=true";
	if(target === opener) setTimeout('self.close();', 250);
}

function observe_scrollers() {
	$$('a.scroll')
		.invoke('observe', 'click', scroll_to)
}

function scroll_to(event) {
	if (event) Event.stop(event);
	link = Event.element(event).href;
	target = link.substring(link.indexOf('#')).replace(/#/, '');
	console.debug(target);
	if (!target) {
		console.error('Target element#ID was not found for scroll_to event');
		return false;
	};
    new Effect.ScrollTo(target, {duration : 0.4});
}

function reset_scroll() {
  new Effect.ScrollTo('header', {duration : 0.4, queue: 'end'});
}

function pingServer() {
	new Ajax.Request('/components/pingresponse.asp', 'get');
}

function showPopup (url,width,height) {
	if(popupwin) {
		popupwin.close();
	}
	//var left = (screen.width-width)/2;
	//var top = (screen.height-(height+90))/2;
	window.name="mainwin";
	popupwin = window.open(url,"popup","resizable=1,statusbar,menubar=no,height="+height+",width="+width+",scrollbars");	
}

function ShowPreview (p) {
	i = p.indexOf('missing');
	if(i===-1) {
		if(PreviewWin) {
			PreviewWin.close();
		}
		
		PreviewWin = window.open("/search/PreviewPicture.asp?picpath="+p,"PreviewWin","Height=500,Width=625,MenuBar=No");
		PreviewWin.focus();
	}
}

function removeContentPadding() {
	document.observe("dom:loaded", function() {
		if ($('content')) {
			if($('contentStripe')) {
			$('content').setStyle({padding:'0px'});
			if ($('crumbline')) {
				$('crumbline').setStyle({paddingLeft:'8px', margin: '0px'});
			}
		}
		}
	});
}

function hideElement (id) {
	var toHide = document.getElementById(id);
	toHide .style.display = "none";
	toHide .style.visibility = "hidden";
}

function showElement(id) {
	var toShow = document.getElementById(id);
	toShow.style.display = "block";
	toShow.style.visibility = "visible";
}

function setCookie(name,value,days) {
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	setCookie(name,"",-1);
}

function loadingMessage(target) {
	$(target).innerHTML ='<span class="smallNote"><img src="/images/illustrations/timer.gif" style="width:16px;" alt="Loading, please wait." align="absmiddle" /> Loading... </span>';
}

function showTimer(target) {
	if ($(target)) $(target).innerHTML ='<div style="font-weight: bold; color:#999; font-size: 9px;"><img src="/images/illustrations/timer.gif" alt="Loading, please wait." style="width:16px; border: 0px none; float: left;" class="timer" /> ...working</div>';
}

function randomizeQstring () {
	var d = new Date();
	var t = d.getTime()*Math.random()*1000000;
	return t;
}

var css_browser_selector = function() {
	var 
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();

function initBasketViewer() {
  
	if ($('basketViewer')) {
	  
	  if ($('basketViewer').up('.dropshadow-container')) $('basketViewer').up('.dropshadow-container').hide(); 
    
    // Watch expansion link:
    $('expandBasketViewer').observe('click',toggleBasketViewer)
                           .observe('mouseover', function(event){ $('expandBasketViewer').addClassName('active') })
                           .observe('mouseout', function(event){ $('expandBasketViewer').removeClassName('active') });
        
    // Style content rows:
    alternateRowColoring('basketViewer');
	}
	
}

function toggleBasketViewer() {
  // Hide the navsearch to prevent it interfering with the viewer:
  if ($('navsearch')) $('navsearch').toggle();
  
  // Show th ebasket viewer and apply a drop shadow:
  if (!$('basketViewer').visible()) $('basketViewer').show();
  if (! $('basketViewer').up('.dropshadow-container') ) applyDropShadow($('basketViewer'));

  var container = $('basketViewer').up('.dropshadow-container');  
  container.toggle();

  if (container.visible()) 
  {
    
    $('expandBasketViewer').down().update('-').addClassName('expanded').removeClassName('collapsed');

		}
  else                     
  {                        
    $('expandBasketViewer').down().update('+').addClassName('collapsed').removeClassName('expanded');
  }
  $('expandBasketViewer').blur();
}

function alternateRowColoring(table) {
  $$('#' + table + ' tr:nth-child(odd)').invoke('addClassName', 'odd');
}

function regularize_panel_heights(){
  if ($$('div.twocol div.panel')) {
    //console.info('Panels in a two column layout found - Applying regular heights...');
    $$('div.twocol div.panel').each(function(element, index){
      
      // Wait for child images to load before applying heights:
      if (element.down('IMG')) {
        new PeriodicalExecuter(function(pe) {
          if (child_images_loaded(element)) 
          {
            //console.debug(element + ' images loaded');
            pe.stop();
            apply_regular_panel_heights(element, index);
          }
          //else 
          //{
          //  console.debug(element + ' images not yet loaded');
          //}
        }, 0.1);        
      }
    });
  }
}

function apply_regular_panel_heights(element, index) {
  //console.debug('Applying regular heights to ' + element + ', with index ' + index);
  if (index % 2) 
  {
        p1 = element.previous('.panel');
        p2 = element;
        p1_height = p1.getHeight();
        p2_height = p2.getHeight();
        //console.debug('p1_height => ' + p1_height + ' / p2_height => ' + p2_height);        

        if (p1_height > p2_height) 
        {
          //console.info('Matching p2 to p1');
          template = p1;
          target = p2;
        } 
        else
        {
          //console.info('Matching p1 to p2');
          template = p2;
          target = p1;          
        }        
        
        cell = (target.down('.cell').getHeight());
        cell_padding = parseInt(target.down('.cell').getStyle('paddingTop').replace('px', ''));
        cell_padding += parseInt(target.down('.cell').getStyle('paddingBottom').replace('px', ''));
        cell_border = parseInt(target.down('.cell').getStyle('borderTopWidth').replace('px', ''));
        cell_border += parseInt(target.down('.cell').getStyle('borderBottomWidth').replace('px', ''));
        cell_increase = (template.getHeight() - target.getHeight()) - (cell_padding + cell_border);
        
    target.setStyle({ 'height' : template.getHeight()-3+'px' });
    target.down('.cell').setStyle({ 'height' : (cell + cell_increase)+'px' });
          
        // Add explicit clearing div:
    new Insertion.After(p2, '<div class="clearing"></div>');
  }
}

function child_images_loaded(element) {
  var images_not_loaded = 0;
  element.getElementsBySelector('IMG').each(function(image){
    if ($(image).loaded) images_not_loaded ++;
  });
  return images_not_loaded == 0 ? true : false;
}

/**
* Event.simulate(@element, eventName[, options]) -> Element
* - @element: element to fire event on
* - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
* - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
* $('foo').simulate('click'); // => fires "click" event on an element with id=foo
**/
(function(){
  
  var eventMatchers = {
    'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
    'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  }
  var defaultOptions = {
    pointerX: 0,
    pointerY: 0,
    button: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    bubbles: true,
    cancelable: true
  }
  
  Event.simulate = function(element, eventName) {
    var options = Object.extend(Object.clone(defaultOptions), arguments[2] || { });
    var oEvent, eventType = null;
    
    element = $(element);
    
    for (var name in eventMatchers) {
      if (eventMatchers[name].test(eventName)) { eventType = name; break; }
    }
 
    if (!eventType)
      throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
 
    if (document.createEvent) {
      oEvent = document.createEvent(eventType);
      if (eventType == 'HTMLEvents') {
        oEvent.initEvent(eventName, options.bubbles, options.cancelable);
      }
      else {
        oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
          options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
          options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
      }
      element.dispatchEvent(oEvent);
    }
    else {
      options.clientX = options.pointerX;
      options.clientY = options.pointerY;
      oEvent = Object.extend(document.createEventObject(), options);
      element.fireEvent('on' + eventName, oEvent);
    }
    return element;
  }
  
  Element.addMethods({ simulate: Event.simulate });
})()


// ###################
// Apply and remove drop shadows to given elements:
function dropShadow(element) {
  // Make sure image is loaded before applying DS.
  // Element height is required to correctly size container.
  // Firing this event on DOM-ready enables the PE quickly,
  // and the DS will be applied as each image loads. Golden.
  
  if (element.nodeName === 'IMG') {
  if (!element.complete) {
	  new PeriodicalExecuter(function(pe) {
      if (element.complete) {
        pe.stop();
        applyDropShadow(element);
      }
    }, 0.25);
  } 
  else {
    applyDropShadow(element);
  }
}
  else {
    if (element.down('img')) {
      new PeriodicalExecuter(function(pe) {
        if (child_images_loaded(element)) {
          //console.debug(element + ' images loaded');
          pe.stop();
    applyDropShadow(element);
  }
        else {
          //console.debug(element + ' images not yet loaded');
        }
      }, 0.25);        
    }
    else {
      applyDropShadow(element);
    }
  }
}

function applyDropShadow(element) {
		element = $(element);
		if (element == undefined) element = self;		
		
		// console.info('Dropshadow element => ' + element);
		
		//Prevent nested drops:
		if (element.down('.dropshadow-container')) { return false; }
		if (element.up('.dropshadow-container')) { return false; }
		//If img is immediately within an A, and agent is IE, apply dropshadow to A tag instead to prevent IE ignoring the link:
		if (element.up().nodeName == "A" && $$('html.ie').length > 0) element = element.up();
		var p = $(element).parentNode;
		var sib = element.next();
		var container = Builder.node('div', {className:'dropshadow-container'},[
			Builder.node('div', {className:'dropshadow-right'}),
			Builder.node('div', {className:'dropshadow-bottom-right'}),
			Builder.node('div', {className:'dropshadow-bottom'})
		]);
	p.insertBefore(container, sib);
	$(container).insertBefore(element, container.down('div.dropshadow-bottom-right'));
	
	//Debugging vars:
	/* 
	var element_set_to_width = element.getWidth()+7+'px';
	var element_width = element.getWidth();
  */
	
	container.setStyle({
	  'position': element.getStyle('position'),
		'width': parseInt(element.getWidth())+8 +'px',
		'height': parseInt(element.getHeight())+7 +'px',
		'clear': element.getStyle('clear'),
		'float': element.getStyle('float'),
	  'marginTop': (element.getStyle('marginTop') ? parseInt(element.getStyle('marginTop')) : 0) + 'px',
	  'marginRight': (element.getStyle('marginRight') ? parseInt(element.getStyle('marginRight')) : 0) + 'px',
	  'marginBottom': (element.getStyle('marginBottom') ? parseInt(element.getStyle('marginBottom')) : 0) + 'px',
	  'marginLeft': (element.getStyle('marginLeft') ? parseInt(element.getStyle('marginLeft')) : 0) + 'px'
	});

	//Remove clearing, float and margin from target-element:
	element.setStyle({
	  'position': 'relative',
	  'clear': 'none',
	  'float': 'right', //fixed to the right to prevent white-space between image and right-shadow
    'margin': '0'
	});
	if (element.nodeName == 'IMG') {
	  element.setStyle({
  	  'borderTop': '1px solid #ddd',
  	  'borderRight': '0px none',
  	  'borderBottom': '0px none',
  	  'borderLeft': '1px solid #ddd'
	  });
	}
	// Remove padding applied to A tags to allow mouseover border:
	if (element.nodeName=="A") element.setStyle({ 'padding': '0px' });
	
	//Get border widths to build shadow dimensions: 
  var top_border_width = element.getStyle('topBorderWidth') ? parseInt(element.getStyle('topBorderWidth')) : 0;
  var right_border_width = element.getStyle('rightBorderWidth') ? parseInt(element.getStyle('rightBorderWidth')) : 0;
  var bottom_border_width = element.getStyle('bottomBorderWidth') ? parseInt(element.getStyle('bottomBorderWidth')) : 0;
  var left_border_width = element.getStyle('leftBorderWidth') ? parseInt(element.getStyle('leftBorderWidth')) : 0;
  
  shadow_right_height = ( parseInt(element.getHeight()) + top_border_width + bottom_border_width );
  shadow_bottom_width = ( parseInt(element.getWidth()) + left_border_width + right_border_width );
  //if (!Prototype.Browser.IE) shadow_right_height = shadow_right_height - 1;

	if (shadow_right_height > 0) {
	container.down('.dropshadow-right').setStyle({
  		'height': shadow_right_height +'px'
	});
  }
  
  /*
  bb.debug('element: ' + element.nodeName);
  bb.debug('element_width: ' + element_width );  
  bb.debug('element_set_to_width: ' + element_set_to_width );
  
  bb.debug('shadow_bottom_width: ' + shadow_bottom_width);
  bb.debug('shadow_right_height: ' + shadow_right_height);
  */
  
	if (shadow_bottom_width > 0) {
	container.down('.dropshadow-bottom').setStyle({
  		'width': shadow_bottom_width +'px'
	});
}
}

function removeDropShadow(element) {
	if (element) {
	  console.debug(element);
		if (element.up().hasClassName('dropshadow-container')) {
			var p = element.up('div.dropshadow-container');
			Element.remove(p.down('div.dropshadow-right'));
			Element.remove(p.down('div.dropshadow-bottom-right'));
			Element.remove(p.down('div.dropshadow-bottom'));
			element.up(1).insertBefore(element, element.up().next());
			Element.remove(p);
		}
	}
	
}

// ###################
// ALBUMS + SAVED SEARCHES + WISHLIST
// ###################
function AddToAlbum() {
	var neglist = ""
	var theForm = document.forms[1]
	var ThisElmt

	for(i=0; i<theForm.elements.length; i++){
		ThisElmt =theForm.elements[i] 
		if((ThisElmt.type == 'checkbox') && (ThisElmt.checked==true) && (ThisElmt.name=='addToAlbum')){
			neglist+= ThisElmt.value + ';'
		}
	}
	if(neglist.charAt(neglist.length-1)==';') { neglist = neglist.substr(0,neglist.length-1) }
	
	window.status=""
	if(winFldr) {
		winFldr.close()
	}
	window.name="mainwin";
	winFldr = window.open("/account/albums/addtoalbum_v2.asp?list="+neglist+";&listmode=search","GetFolder","statusbar,menubar=no,height=350,width=530,scrollbars=yes")
	}

function AddNegToAlbum(neg) {
  if ((neg == '' || neg === undefined) && $F('neg')) neg = $F('neg');
	window.name="mainwin";
	window.status=""
	if(winFldr) {
		winFldr.close()
	}
	winFldr = window.open("/account/albums/addtoalbum_v2.asp?list="+neg+";&listmode=search","GetFolder","statusbar,menubar=no,height=350,width=530,scrollbars=yes")
}

function AddBookCaptionToAlbum(captionid) {
	window.status=""
	if(winFldr) {
		winFldr.close()
	}
	window.name="mainwin";
	winFldr = window.open("/account/albums/addtoalbum_v2.asp?list="+captionid+";&listmode=bookcaption","GetFolder","statusbar,menubar=no,height=350,width=530,scrollbars=yes")
}

function GetSLFolder() {
	//List current folders/create a new one
	var obj = document.all.selimages
	var strTmp = ""
	if(obj.length) {
		// more than one image shown	
		for(var x=0;x<obj.length;x++) {
				if(obj[x].checked) {
					strTmp += obj[x].value + ";"
				}
		}
	} else {
		if(obj.checked==true) {
			strTmp = obj.value + ";"
		}
	}
	if(strTmp=="") {
		alert("You have no images selected.")
	} else {
		if(winFldr) {
			winFldr.close()
		}
		winFldr = window.open("/content/components/shortlist/SelectFolder.asp?list="+strTmp,"GetFolder","statusbar,menubar=no,height=350,width=530,scrollbars=yes")
	}
}

function DeselectAll() {
	if(document.all.selimages) {
		for(var x=0;x<document.all.selimages.length;x++) {
			document.all.selimages[x].checked = false;
		}
	}
}

function SelectAll() {
	for(var x=0;x<document.all.selimages.length;x++) {
		document.all.selimages[x].checked = true;
	}
}

function AddToWishList(pid,neg) {
	document.frmProductInfo.productid.value = pid
	document.frmProductInfo.neg.value = neg
	document.frmProductInfo.mode.value = "wishlist"
	document.frmProductInfo.submit()
}

function CheckAddFromWishList() {	
	var FormOK = false
	if(document.frmWL.chkSelect.length) {
		for(var x=0; x<document.frmWL.chkSelect.length;x++) {
			if(document.frmWL.chkSelect[x].checked==true) {
				FormOK = true
				break;
			}
		}
	} else {
		if(document.frmWL.chkSelect.checked==true) {
			FormOK = true;
		} else {
			FormOK = false;
		}
	}
	if(FormOK==true) {
		return true
	} else {
		alert("You have not selected any Wish List items to add to your basket.")
		return false
	}
}	

function RemoveSavedSearch(rid) {
	if(confirm("Are you sure you want to remove this saved search?")==true) {
		document.frmSS.rid.value = rid
		document.frmSS.submit()
	}
}

function selectimg() {}

function deselectimg() {}

function Browser() {
	var ua, s, i;
	this.isIE = false;
	this.isNS = false;
	this.version = null;
	ua = navigator.userAgent;
	s = "MSIE";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isIE = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	s = "Netscape6/";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = parseFloat(ua.substr(i + s.length));
		return;
	}
	// Treat any other "Gecko" browser as NS 6.1.
	s = "Gecko";
	if ((i = ua.indexOf(s)) >= 0) {
		this.isNS = true;
		this.version = 6.1;
		return;
	}
}

function deleteMemory(hascomments,memid,custid,backtopage) {
	var msg = ""
	if(hascomments) 
	{
		msg+="This memory has comments attached and will not be deleted automatically.\n"
		msg+="The request for the removal of this memory will be sent to the moderator for approval.\n"
		msg+="You will be notified by email whether or not the memory has been removed.\n\n"
	}
	msg+="Are you sure you want to delete this memory?\n\nThis action cannot be undone."
	if(confirm(msg)) 
	{
		document.location.href="/pageloader.asp?page=/account/memories/editmemory.asp&mode=delete&memid="+memid+"&customerid="+custid+"&backto="+backtopage
	}
}

// ###################
// Prevent console debugging errors in browsers without Firebug installed:
if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}
var log = {
  toggle: function() {},
  move: function() {},
  resize: function() {},
  clear: function() {},
  debug: function() {},
  info: function() {},
  warn: function() {},
  error: function() {},
  profile: function() {}
};


// Site-wide message sending functions (used for send messages to memory contributors,etc) 
function SendUserAMessage(FromCID, ToCID, ID) {
	var msg="";
	if($('_messagesubject').value=='') { msg+=' - Subject cannot be blank\n' }
	if($('_messagecontent').value=='') { msg+=' - The message cannot be blank\n' }
	if((FromCID=='') || (ToCID=='')) { msg+=' - Missing parameters!\n' }
	
	var s = $('_messagesubject').value;
	var m = $('_messagecontent').value;
	
	//m = m.replace(/"/g,'/"')
	
	params = 's='+escape(s)+'&m='+escape(m)+'&f='+FromCID+'&t='+ToCID+'&i='+ID
	
	if(msg=='') {
		//var res = new Ajax.Request(url,{method: 'post',parameters: params, onComplete: ListOrders_Complete, onFailure: ListOrders_Error, asynchronous: true});	

		//new Ajax.Request('/account/messages/_sendmessage.asp', {
		new Ajax.Request('/functions/_sendmessage.asp', {
			parameters: params,
			onComplete: function(returnValue) {

				if(returnValue.responseText=='ok') {					
				alert('Message Sent!')
					myLightwindow.deactivate()
				} else if(returnValue.responseText!='error') {
					alert('There was an error sending your message - '+returnValue.responseText)
				} else {
					alert('There was an error sending your message.')
				}

				//$('adding_new_rule_spinner').remove();
				// Insert the returned HTML at the bottom of the rule container:
				//$('rules_container').insert({ bottom: returnValue.responseText});
				// Watch for changes to the rule name/value elements:
				//setup_rule_observers();
			}
		})		
	} else {
		alert("Error sending your message:\n"+msg);
	}
}

function verifySeal() {
	var bgHeight = '620';
	var bgWidth = '536';
	var url = 'https://seal.godaddy.com:443/verifySeal?sealID=UyKqcJhOfTOuH1Ni97n7D4P8YLOcbOZdVVY4nGpdzG6vXPAokaf8aT1QdX6g';
	window.open(url,'SealVerfication','location=yes,status=yes,resizable=yes,scrollbars=no,width=' + bgWidth + ',height=' + bgHeight);
}

