/* TIGER Page JS */

/* Create a YUI JavaScript namespace 'Natural' to separate the two JS libraries
 * and prevent conflicts. */
YAHOO.namespace ('tiger');

/* Assign the YAHOO.natural namespace to a shorter referece var for smaller,
 * easier referencing. */
var TIGER = YAHOO.tiger;

/* Get the UserAgent
 * To test for the UA use:
 * if (NAT.ua.gecko > 0) 	{}	// e.g. Firefox
 * if (NAT.ua.ie 	> 0) 	{}	// Microsoft Internet Explorer
 * if (NAT.ua.opera)	 	{}	// Opera
 * if (NAT.ua.webkit) 	 	{}	// Safari, Webkit  */
TIGER.ua = YAHOO.env.ua;

var Dom = YAHOO.util.Dom;
var Event = YAHOO.util.Event;
var Element = YAHOO.util.Element;
var Anim = YAHOO.util.Anim;
var ColorAnim = YAHOO.util.ColorAnim;

TIGER.containerHeights = [];
TIGER.animOpen = [];
TIGER.animClose = [];
TIGER.animFadein = [];
TIGER.animFadeout = [];

// If your images will be served from a different server,
// edit the next line ie : TIGER.imagepath = 'http://mysite.com/image/path/';
TIGER.imagepath = 'http://img.en25.com/Web/NestlePurinaPetCareCompany/';

// BEGIN CALENDAR //
/*
 * Functions to add a calendar to an input field
 * The function accepts an array of id's as str or an array of el ref.
 * Automatically adds the calendar image
 *
 * Example: TIGER.autoCalendar(['departDate','arriveDate']);
 *
 * or
 *
 * 	var oOptions = {
 *		'DATE_FIELD_DELIMITER' : '.',
 *		'MDY_DAY_POSITION' : 3,
 *		'MDY_MONTH_POSITION' : 2,
 *		'MDY_YEAR_POSITION' : 1
 *	};
 *	TIGER.autoCalendar(['effdate','endeffdate'],oOptions);
 */

TIGER.autoCalendar = function(elArr,oOptions){
	var elDate, showBtn;

	var i=0;
    for(i in elArr){
        elDate = Dom.get(elArr[i]);

        // Self-generate a calendar button as follows
    	// <img id="cal_X" src="calendar.png" width="16" height="16" alt="Show Calendar" >
		var img = TIGER.html.createElement(
			'img', {
				'id' : 'cal_'+i,
				'class' : 'calendar_icon',
				'src' : TIGER.imagepath + 'calendar.png',
				'width' : '16',
				'height' : '16',
				'alt' : 'Show Calendar'
				},
			elDate,
			'after'
		);

		showBtn = Dom.get('cal_'+i);

		Event.on(showBtn, 'click', function() {
			// Call helperFunction here
			TIGER.addCalendar(this,oOptions);
		});

		i++;

    }
}

// Calendar helper Function
TIGER.addCalendar = function(showBtn,oOptions)
{
	var calPanel, calendar, elDate;

	elDate = Dom.getPreviousSibling(showBtn).value;

	// Function to pre-pad dates
	var pad = function(str){return (str.toString().length == 1) ? '0'+str : str;}

    // Dialog Creation - Wait to create the Dialog, and setup document click listeners, until the first time the button is clicked.
    if (!calPanel) {

        // Hide Calendar if we click anywhere in the document other than the calendar
        Event.on(document, 'click', function(e) {
            var el = Event.getTarget(e);
            var calPanelEl = calPanel.element;
            if (el != calPanelEl && !Dom.isAncestor(calPanelEl, el) && el != showBtn && !Dom.isAncestor(showBtn, el)) {
                calPanel.hide();
            }
        });

        calPanel = new YAHOO.widget.Panel('tiger_calendar', {
            visible:false,
            context:[showBtn.previousSibling, 'tl', 'bl',,[2,3]],
            // constraintoviewport:true,
            effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.25},
            draggable:false,
            close:false
        });

        // calPanel.setHeader('Pick A Date');
        calPanel.setBody('<div id="cal"></div>');
        calPanel.render('tiger_dhtml');

        calPanel.showEvent.subscribe(function() {
            if (YAHOO.env.ua.ie) {
                // Since we're hiding the table using yui-overlay-hidden, we
                // want to let the calPanel know that the content size has changed, when
                // shown
                calPanel.fireEvent('changeContent');
            }
        });
    }

    // Calendar Creation - Wait to create the Calendar until the first time the button is clicked.
    if (!calendar) {

        // See YUI Calendar for all possible calendar properties
    	oOptions = (typeof oOptions == 'object') ? oOptions : {iframe:false,hide_blank_weeks:true,navigator:true};

        calendar = new YAHOO.widget.Calendar('cal', oOptions);
        calendar.cfg.setProperty('selected',Dom.getPreviousSibling(showBtn).value);
        calendar.render(document.body);

        calendar.selectEvent.subscribe( function() {
            if (calendar.getSelectedDates().length > 0) {

            	var selDate = calendar.getSelectedDates()[0];
                var delStr = calendar.cfg.getProperty('DATE_FIELD_DELIMITER');
                var dayPos = calendar.cfg.getProperty('MDY_DAY_POSITION');
                var monPos = calendar.cfg.getProperty('MDY_MONTH_POSITION');
                var yerPos = calendar.cfg.getProperty('MDY_YEAR_POSITION');

                var dateArr = new Array();
                dateArr[dayPos] = selDate.getDate();
                dateArr[monPos] = selDate.getMonth()+1;	// Months are 0-11 evidently, need to add +1
                dateArr[yerPos] = selDate.getFullYear();

                Dom.getPreviousSibling(showBtn).value = pad(dateArr[1]) + delStr + pad(dateArr[2]) + delStr + pad(dateArr[3]);

            } else {

            	elDate.value = '';

            }
            calPanel.hide();
        });

        calendar.renderEvent.subscribe(function() {
            // Tell Dialog it's contents have changed, which allows
            // container to redraw the underlay (for IE6/Safari2)
            calPanel.fireEvent('changeContent');
        });
    }

    var seldate = calendar.getSelectedDates();

    if (seldate.length > 0) {
        // Set the pagedate to show the selected date if it exists
        calendar.cfg.setProperty('pagedate', seldate[0]);
        calendar.render();
    }

	// uncomment and adjust to prevent calendars from being shown on disabled fields
	// if (showBtn.previousSibling.disabled != true && !showBtn.previousSibling.hasAttribute('disabled')){
    // if (Dom.getPreviousSibling(showBtn).disabled != false){
    	calPanel.show();
    // }

}

// END CALENDAR //



TIGER.panels = {};
TIGER.panels.sla = function(){
	this.sla.panel = new YAHOO.widget.Panel(
	'sla-OFF',
	{
		width: '800px',
		height: '600px',
		visible: false,
		// constraintoviewport: true,
		underlay:"shadow",
		close: true,
		fixedcenter: true,
		draggable: false,
		modal: true,
		effect: {effect:YAHOO.widget.ContainerEffect.FADE, duration:0.3}
	});
	this.sla.panel.render('tiger_dhtml');
};

TIGER.panels.proc_image = function(){
	this.proc_image.panel = new YAHOO.widget.Panel(
	'proc_image',
	{
		width: '840px',
		height: '600px',
		visible: false,
		// constraintoviewport: true,
		underlay:"shadow",
		close: true,
		fixedcenter: true,
		draggable: false,
		modal: true,
		effect: {effect:YAHOO.widget.ContainerEffect.FADE, duration:0.3}
	});
	this.proc_image.panel.render('tiger_dhtml');
};


TIGER.offerCode = {
	init : function(){
		Event.on(['ShortName'],'keyup',TIGER.offerCode.update);
		Event.on('Brand','change',TIGER.offerCode.update);
		Event.on('LDate','change',TIGER.offerCode.update);
	},

	update : function(){

		var LDate = Dom.get('LDate');
		var brand = Dom.get('Brand');
		var sname = Dom.get('ShortName');

		sname.value = sname.value.toUpperCase();

		if(TIGER.util.isDate(LDate.value))
		{
			var aLDate = LDate.value.split('/');

			var year = Dom.get('LaunchYear');
			var month = Dom.get('LaunchMonth');
			var day = Dom.get('LaunchDay');
			var vs = '-';

			month.value = aLDate[0];
			day.value = aLDate[1];
			year.value = aLDate[2];

			Dom.get('OfferCode').value = year.value + vs + month.value + vs +  day.value + vs + brand.value + vs + sname.value;

		}

	}
}


TIGER.animateElement = {
	init : function(els){

		els = Dom.get(els);

		Dom.batch(
			els,
			function(el){
				// remember their heights
				TIGER.containerHeights[el.id] = el.offsetHeight;

				// hide elements
				Dom.setStyle(el, 'opacity', 0);

				// setup the open and closing animations
				TIGER.animOpen[el.id] = new Anim(el, {height:{to:TIGER.containerHeights[el.id]}}, 0.3);
				TIGER.animFadein[el.id] = new Anim(el, {opacity:{to:1}}, 0.3);
				TIGER.animOpen[el.id].onComplete.subscribe(function(){
					el.style.height = 'auto';
					TIGER.animFadein[el.id].animate();
				})

				TIGER.animFadeout[el.id] = new Anim(el, {opacity:{to:0}}, 0.3);
				TIGER.animClose[el.id] = new Anim(el, {height:{to:0}}, 0.3);
				TIGER.animFadeout[el.id].onComplete.subscribe(function(){TIGER.animClose[el.id].animate();})
			}
		);

	},

	toggle : function(elClose,elOpen){
		elClose = Dom.get(elClose);
		elOpen = Dom.get(elOpen);
		if (elClose.offsetHeight != 0){
			TIGER.animFadeout[elClose.id].animate();
			TIGER.animOpen[elOpen.id].animate();
			// Dom.getAncestorByClassName(elOpen,'element_container').style.height = 'auto';
		}
		else
		{
			TIGER.animOpen[elOpen.id].animate();
			// Dom.getAncestorByClassName(elOpen,'element_container').style.height = 'auto';
		}
	},

	open : function(el){
		el = Dom.get(el);
		if (el.offsetHeight == 0){
			TIGER.animOpen[el.id].animate();
			Dom.get(el).style.height = 'auto';
		}
	},

	close : function(el){
		el = Dom.get(el);
		if (el.offsetHeight != 0){
			TIGER.animFadeout[el.id].animate();
		}
	}
}

TIGER.animCheckbox = function(el,elm){
	if(el.checked){
		TIGER.animateElement.open(elm);
	}
	else
	{
		TIGER.animateElement.close(elm);
	}
}

TIGER.resizeTextareas = function(aEls){
	aEls = Dom.get(aEls);
	TIGER.resizeTextareas.resize = []
	Dom.batch(
		aEls,
		function(el){
			TIGER.resizeTextareas.resize[el.id] = new YAHOO.util.Resize(el.id, {
				handles: ['b'],
				proxy: false,
				minHeight: 20,
				minWidth: 560,
				animate: true,
				animateDuration: .30,
				animateEasing: YAHOO.util.Easing.easeOut
			});
		}
	);
}

/* TIGER.setFormMessage helps to abstract the TIGER.message class by keeping it
 * independent of other code. That way we can use the validator to test
 * all kinds of fields and not just generate messages. */
TIGER.setFormMessage = function(oMessage){
	if (oMessage.message.length > 0)
	{
		/* Message Object:
		 * {
		 * 		message		: {string},
		 * 		sourceElm	: {el || string} (usually null except for form messages),
		 * 		targetElm	: {el || string} (defaults to system_messages),
		 * 		sclass		: {string} (optional, defaults to 'alert')
		 * }
		 */

		TIGER.message.show(oMessage);
	}
};


TIGER.checkPersonalization = function(box,el)
{
	el = Dom.get(el);
	if(box.checked) {
		Dom.addClass(el,'R');
		TIGER.validate.init(el,TIGER.setFormMessage);
		Dom.addClass(Dom.getPreviousSibling(el),'required');
	}
	else {
		Dom.removeClass(el,'R');
		var callback = TIGER.setFormMessage;
		Event.removeListener(el,'blur',function(e){ TIGER.validate(this,callback); });
		Dom.removeClass(Dom.getPreviousSibling(el),'required');
	}
};

// run these initializers once the dom is ready

Event.onDOMReady(function(){

	// we need to do this from the inside out. get the heights of the
	// inner-most elements first and then work outward ...
	var els = [
		'recurringcriteria_container',
		'ifyesprovideoffercode_container',

		'Element1Email-MultipleVersions_container',
		'Element2Email-MultipleVersions_container',
		'Element3Email-MultipleVersions_container',

		'Element1Email-Coupon_container',
		'Element2Email-Coupon_container',
		'Element3Email-Coupon_container',

		'element1email_container',
		'element1landing_container',

		'element2email_container',
		'element2landing_container',

		'element3email_container',
		'element3landing_container',

		'Element1Email-ABCSubjectLineTesting_container',
		'Element2Email-ABCSubjectLineTesting_container',
		'Element3Email-ABCSubjectLineTesting_container',
		
		'Element1LP-Coupon_container',
		'Element2LP-Coupon_container',
		'Element3LP-Coupon_container',

		'Element1Email-ShareToSocial_container',
		'Element2Email-ShareToSocial_container',
		'Element3Email-ShareToSocial_container',

		'Element1Email-Personalization_container',
		'Element2Email-Personalization_container',
		'Element3Email-Personalization_container'

	];

	// initialize animated elements
	TIGER.animateElement.init(els);

	// now collapse them
	Dom.setStyle(els,'height',0);

	// now get the next group of parent containers
	els = [
		'element1_container',
		'element2_container',
		'element3_container'
	];

	// initialize animated elements
	TIGER.animateElement.init(els);

	// now collapse them
	Dom.setStyle(els,'height',0);


	// initialize the panels
	TIGER.panels.sla();
	TIGER.panels.proc_image();

	// initialize the calendars
	TIGER.autoCalendar([
		'LDate',
		'Element1LaunchDate',
		'Element1LP-SweepstakesEndDate',
		'Element2LaunchDate',
		'Element2LP-SweepstakesEndDate',
		'Element3LaunchDate',
		'Element3LP-SweepstakesEndDate',
		'Element1Email-Coupon-ExpirationDate',
		'Element2Email-Coupon-ExpirationDate',
		'Element3Email-Coupon-ExpirationDate',
		'Element1LP-Expiry',
		'Element2LP-Expiry',
		'Element3LP-Expiry'
	])

	// initialize the offer code
	TIGER.offerCode.init();

	// resize-able textareas
	TIGER.resizeTextareas([
		'AgencyFriendlySeedList',
		'BrandFriendlySeedList',
		'PleaseExplainAnyOtherComponentsDeliverables'
	]);

	// IE doesn't handle the burried DHTML well at all. So we
	// put in a browser test to add DHTML for non-IE browsers
	els = [
		'Element1Email-MultipleVersions-Description',
		'Element1LP-QuestionSetVSS'
	];
	if (YAHOO.env.ua.ie == 0) {
		TIGER.resizeTextareas(els);
	} else {
		Dom.setStyle(els,'height', 80);
		Dom.setStyle(els,'overflow', 'auto');
	}


	// set the timestamps
	var timestamp = TIGER.util.date('Y-m-d H:m:s');
	Dom.get('DateSubmitted').value = timestamp;
	Dom.get('system_date').innerHTML = timestamp;

	// TIGER.message.init();
	TIGER.validate.init(['CampaignInitiation'],TIGER.setFormMessage);

});

