/**
 * General utility functions
 * @author Scott Murphy
 * 
 * Copyright (c) 2008 Pictage Inc.
 * ALL RIGHTS RESERVED
 */

$$('a.tblank').set('target', '_blank');

var IFrame1 = new Native({

	name: 'IFrame1',

	generics: false,

	initialize: function(){
		var params = Array.link(arguments, {properties: Object.type, iframe: $defined});
		var props = params.properties || {};
		var iframe = $(params.iframe) || false;
		var onload = props.onload || $empty;
		delete props.onload;
		props.id = props.name = $pick(props.id, props.name, iframe.id, iframe.name, 'IFrame_' + $time());
		iframe = new Element(iframe || 'iframe', props);
		var onFrameLoad = function(){
			var host = $try(function(){
				return iframe.contentWindow.location.host;
			});
/*			if (host && host == window.location.host || !host){
				var win = new Window(iframe.contentWindow);
				new Document(iframe.contentWindow.document);
				$extend(win.Element.prototype, Element.Prototype);
			} 
			onload.call(iframe.contentWindow, iframe.contentWindow.document);*/
		};
		(window.frames[props.id]) ? onFrameLoad() : iframe.addListener('load', onFrameLoad);
		return iframe;
	}

});

Window.implement({
	$E: function(selector){
		return this.document.getElement(selector);
	}
});

function displayDDLicenseAgreement()  {
	DDLicenseAgreePopup = new PopUp({width:540,content:'DDLicenseAgreement', title:'Personal Use License Agreement', closeAction:function() {}});
	DDLicenseAgreePopup.show();
}

// swapFullImage and getStandardImage are used in Books Pages and Canvas Prints
function swapFullImage(imageCSS) {
	$('fullImage').set('class', imageCSS);
}
	
function getStandardImage(product) {
	$('fullImage').set('class', ( product !== 'memory' ) ? product : product+'OneImage');
}

function displayReminderPopup(contentId, titleTxt) { 
	new PopUp( {	width:540,
				content: contentId, 
				title:titleTxt, 
				closeAction:function() {}
			}).show();
}

// Blocks clicks on element while function is processed
function blockClicks( el, func )
{
	el = $(el); // ie6
	if ( el.retrieve('clicked') )
		return;
	el.store('clicked', true);
	func();
	el.store('clicked', false);
}

/**
 *	Causes the inputs form to submit if the enter key is pressed.
 *  form parameter should not normally be passed
 */
function enableEnterSubmit( input, form )
{
	input.addEvent('keypress', function(event) {
		if (event.key == 'enter') {
			if ($defined(form))
				form.submit();
			else
				input.form.submit();
		}
	}); 	
}

function countdownTimer(display) {
	var msInSec = 1000;
	var msInMinute = msInSec * 60;
	var msInHour = msInMinute * 60;
	var msInDay = msInHour * 24;
	
	var localGmtOffset = new Date().getTimezoneOffset() * msInMinute;
	var pstOffset = 8 * msInHour;
	
	var pad = function(num) {
		if (num.toString().length < 2) {
			num = "0" + num;
		}
		return num;
	};
	
	var calcOffset = function(date, offset) {
		return new Date(date.getTime() + offset);
	};

	var getGmt = function() {
		var d = new Date();
		return calcOffset(d, localGmtOffset);
	};

	var changePstToGmt = function(date) {
		return calcOffset(date, pstOffset);
	};
	
	var targetDate = changePstToGmt(new Date(2010, 11, 2, 23, 59, 59)); // example: dec 2, 2010 at 11:59pm. Month, hour, minute and seconds are zero-based. Day is one-based.
	
	var countdown = setInterval(function(){
		var diff = targetDate.getTime() - getGmt().getTime();
		if (diff > 0) {
			//var days = pad(Math.floor(diff / msInDay));
			//var r = diff % msInDay;
			
			var hours = pad(Math.floor(diff / msInHour));
			r = diff % msInHour;
			
			var mins = pad(Math.floor(r / msInMinute));
			r = r % msInMinute;
			
			var secs = pad(Math.floor(r / msInSec));
			
			/*** update display here ***/
			display.setStyle('visibility','visible').set('html',hours+":"+mins+":"+secs);
		}
		else {
			clearInterval(countdown);
		}
	}, 1000);
}

window.addEvent("domready", function() {
	if($defined($('ceeDivLayer')))
		displayReminderPopup('ceeDivLayer', 'Extend Event');

	if(!$defined('ceeDivLayer') && $defined(releaseReminderTitle))
		displayReminderPopup('releaseReminder', releaseReminderTitle);
	
	if ( $defined( $E('div#studioCard .studioLogo') ) && studioWebSite != '' ) {
		$E('div#studioCard .studioLogo').setStyle('cursor','pointer');
		$E('div#studioCard .studioLogo').addEvent('click', function() {
			window.open(studioWebSite);
		});
	}
	
	countdownTimer($$('.freeShippingBannerCountdown'));
	
	$$('span.lblPagination').each( function(el) {
		el.addEvent('click', function(event) {
			var scrollSize = window.getScrollSize();
			var elementLocation = el.getCoordinates();
			var elementSize = el.getSize();
			var span = $(event.target);
			
			function doJump() {
				var pageNum = jump.getElement('input[type=text]').get('value');
				if ( pageNum.trim() != '' ) {
					pageNum = pageNum.toInt();
					if (pageNum)
						window.location = baseUrl+'&page='+(pageNum - 1);
				}
			}
			
			var jump = new Element('div', {
				'class':'windowJumpToPage',
				'html':'<ul><li>Jump to:</li><li><input type="text" id="pageNumber"/></li><li><input type="button" class="button" value="Go"/></li></ul>',
				'styles': {
					'position':'absolute',
					'z-index':'1001',
					'top': (elementLocation.top + elementSize.y) + 5,
					'left': (elementLocation.left - ( elementSize.x / 2) - 3),
					'opacity': '0'
				},
				events	 : {
					'keydown' : function(event) {
						if (event.key == "enter")
							doJump();
					}
				}					
			}).inject( document.body );
			jump.setStyle('visibility','visible');
			
			jump.getElement('input[type=button]').addEvent('click', doJump );
				  
			var cover = new Element('div', {
				'class':'paginationCover',
				'styles': {
					'position':'absolute',
					'z-index':'999',
					'opacity':'0',
					'top':'0',
					'left':'0',
					'width': scrollSize.x + 'px',
					'height': scrollSize.y + 'px'
				},
				'events': {
					'click': function(event) {
						jump.dispose();	
						this.dispose();
					}
				}
			}).inject( document.body );
			cover.setStyle('visibility','visible');
			jump.fade('1'); 
			jump.getElement('input[type=text]').focus();		
		});
	});
});

Number.implement({
	/*
	Property: numberFormat
		Format a number with grouped thousands.

	Arguments:
		decimals, optional - integer, number of decimal percision; default, 2
		dec_point, optional - string, decimal point notation; default, '.'
		thousands_sep, optional - string, grouped thousands notation; default, ','

	Returns:
		a formatted version of number.

	Example:
		>(36432.556).numberFormat()  // returns 36,432.56
		>(36432.556).numberFormat(2, '.', ',')  // returns 36,432.56
	*/

	numberFormat : function(decimals, dec_point, thousands_sep) {
		decimals = Math.abs(decimals) + 1 ? decimals : 2;
		dec_point = dec_point || '.';
		thousands_sep = thousands_sep || ',';
	
		var matches = /(-)?(\d+)(\.\d+)?/.exec((isNaN(this) ? 0 : this) + ''); // returns matches[1] as sign, matches[2] as numbers and matches[3] as decimals
		var remainder = matches[2].length > 3 ? matches[2].length % 3 : 0;
		return (matches[1] ? matches[1] : '') + (remainder ? matches[2].substr(0, remainder) + thousands_sep : '') + matches[2].substr(remainder).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + 
				(decimals ? dec_point + (+matches[3] || 0).toFixed(decimals).substr(2) : '');
	}
});
