/**
 * functions.js
 *
 * Provides standalone functions to enrich or extend the website experience.
 * Some of these functions rely on mootools to be pre-loaded.
 */

/**
 * Constants defined here can be accessed from all functions
 */
var _SPACER_IMAGE = '../images/spacer.gif'; // define spacer image used by alphapng functions


/**
 * apply filters (regular expressions allowed) against a block of text)
 *
 * @param string text
 * @param array array of filters
 * @return string
 */
function filterText(text, filters)
{
	for (x = 0; x < filters.length; x++)
	{
		var find = new RegExp(filters[x].name);
		var replace = filters[x].value;
		text = text.replace(find, replace);
	}

	return(text);
}

/**
 * include an external HTML file for inclusion inside another HTML element
 *
 * @param string dom id
 * @param string url
 * @param array array of filters
 * @param string function to execute on include completion
 * @return void
 */
function include(id, url, filters, formId, onComplete)
{

	//set method default to 'get'. But check to see if it needs to be post...
	var method = "get";

	if (formId && $(formId).getProperty("method") != "") {
		method = $(formId).getProperty("method");
	}

	// default text to display when external content could not be loaded
	var failureText = 'Sorry, but this content is currently unavailable. Please contact technical support for assistance.';

	// actions to perform after a response is received
	var loadSuccess = function(responseText)
	{
		if (filters != undefined)
		{
			responseText = filterText(responseText, filters);
		}

		$(id).setHTML(responseText);
		this.evalScripts(onComplete);
	};

	// actions to perform when a request fails
	var loadFailure = function()
	{
		$(id).setHTML(failureText);
	};

	// AJAX call here
	var ajaxOptions = {
		'method':		method,
		'onSuccess':	loadSuccess,
		'onFailure':	loadFailure
	};

	var ajaxRequest = new Ajax(url, ajaxOptions).request();
}

/**
 * include an external HTML file for inclusion inside another HTML element
 * and display using a fancy animation
 *
 * @param string dom id
 * @param string url
 * @param array array of filters
 * @param string function to execute on include completion
 * @return void
 */
function includeFancy(id, url, filters, formId, onComplete)
{
	//set method default to 'get'. But check to see if it needs to be post...
	var method = "get";

	if (formId && $(formId).getProperty("method") != "") {
		method = $(formId).getProperty("method");
	}

	// default text to display when external content could not be loaded
	var failureText = 'Sorry, but this content is currently unavailable. Please contact technical support for assistance.';

	// effects delay
	var duration = 1000;

	// default effects used for showing new content
	var fadeFx = new Fx.Style($(id), 'opacity', {'duration':duration, 'wait':false});
	var slideFx = new Fx.Slide($(id), {'duration':duration, 'wait':false});

	// actions to perform after a response is received
	var loadSuccess = function(responseText)
	{
		if (filters != undefined)
		{
			responseText = filterText(responseText, filters);
		}

		$(id).setHTML(responseText);
		fadeIn();
		this.evalScripts(onComplete);
	};

	// actions to perform when a request fails
	var loadFailure = function()
	{
		$(id).setHTML(failureText);
		fadeIn();
	}

	// perform ajax request
	var loadUrl = function()
	{
		// AJAX call here
		var ajaxOptions = {
			'method':		method,
			'onSuccess':	loadSuccess,
			'onFailure':	loadFailure
		};

		var ajaxRequest = new Ajax(url, ajaxOptions).request();
	}

	var fadeOut = function()
	{
		fadeFx.start(1,0);
		slideFx.slideOut();
	}

	var fadeIn = function()
	{
		slideFx.slideIn();
		fadeFx.start(0,1);
	}

	// let's get started
	fadeOut();
	(function() { loadUrl() }).delay(duration);
}

/**
 * include an external HTML file (resulting from a form submission) for inclusion inside another HTML element
 *
 * @param string dom id
 * @param string url
 * @param string form dom id or name
 * @param array array of filters
 * @param string function to execute on include completion
 * @return void
 */
function includeSubmit(id, url, formId, filters, onComplete)
{
	include(id, url, filters, formId);
}

/**
 * Remove pre seeded text within input box and set focus to this box
 */
function rewardsNumberFocus()
{
	if (!$("dswRewardsType_1").checked) {
		$("dswRewardsType_1").checked = true;
	}

	if ($("rewardsNumber").value == "" || $("rewardsNumber").value == "Enter Rewards Number") {
		$("rewardsNumber").value = "";
	}

	$("rewardsNumber").style.color = "#000000";
	$("rewardsNumber").focus();
}

/**
 * onchange event to show Fit Information on FitPerfect Overlay.
 */
function showFitInfo() {
	$("promoInfo").setStyle('display', 'none');
	$("fitInfo").setStyle('display', 'block');
}

/**
 * onchange event to close Fit Information on FitPerfect Overlay.
 */
function closeFitInfo() {
	$("fitInfo").setStyle('display', 'none');
	$("promoInfo").setStyle('display', 'block');
}

/**
 * onchange event to toggle style image on FitPerfect Overlay.
 */
function toggleStyleImage(styleID, styleAlt) {
	$("styleImage").src = "../images/style_" + styleID + ".gif";
	$("styleImage").alt = styleAlt;
}

/**
 * onchange event to check if user entered any data. If not, then add back text.
 */
function rewardsNumberCheck()
{
	if ($("rewardsNumber").value == "") {
		$("rewardsNumber").style.color = "#cccccc";
		$("rewardsNumber").value = "Enter Rewards Number";
	}
}

/**
* Brands Page Input Search
*/
function searchBrandsOnClick()
{
	if ($("brandSearchInput").value == "" || $("brandSearchInput").value == "Enter a brand name") {
		$("brandSearchInput").value = "";
		$("brandSearchInput").style.color = "#000000";
		$("brandSearchInput").focus();
	}
}

function searchBrandsOnBlur()
{
	if ($("brandSearchInput").value == "") {
		$("brandSearchInput").style.color = "#cccccc";
		$("brandSearchInput").value = "Enter a brand name";
	}
}

/**
* Simple slide toggler using the Global Storage object
*
* Note: This assumes the starting position for the div
*       is visible (out).
*/
function toggleSlide(id, options) {
	if(Global.get('slide' + id) == null) {
		Global.set(new Fx.Slide($(id), options), 'slide' + id);
	}

	Global.get('slide' + id).toggle();
}

function toggleFadingSlide(id, options) {
	if(Global.get('slide' + id) == null) {
		Global.set(new Fx.Slide($(id), options), 'slide' + id);
	}
	if(Global.get('fade' + id) == null) {
		Global.set(new Fx.Style($(id), 'opacity', options), 'fade' + id);
	}

	var opacity = $(id).getStyle("opacity");

	if(opacity == 0) {
		opacity = 1;
	}
	else {
		opacity = 0;
	}

	Global.get('slide' + id).toggle();
	Global.get('fade' + id).start(opacity);
}

/**
 * Function that handles the button action states for mouse over,
 * disabled, selected and unselected. Handles a maximum number of
 * selections if valid.
 *
 * @param string dom id of button
 * @param string action event that is firing
 * @param int maximum number of selections that can be made
 * @return void
 *
 * @author Josh Zeigler <jzeigler@resource.com>
*/

function buttonAction(id, action, maxSelections) {
	// check to see if button is disabled by classname
	if ($(id).className != "buttonDisabled") {
		//check button action to preform tasks
		if (action.toLowerCase() == "onclick") {
			//blur out the button so it doesn't get the annoying focus borders
			$(id).blur();

			if ($(id).className == "buttonActive") {
				$(id).className = "buttonNormal";
			}
			else {
				// select all active button elements in the button container
				var activeButtons = $ES("#" + $(id).parentNode.id + " button.buttonActive");

				// if there are too many selections, turn off the first selected button.
				if (activeButtons.length > 0 && maxSelections != undefined && maxSelections >= activeButtons.length) {
					activeButtons[0].className = "buttonNormal";
				}

				$(id).className = "buttonActive";
			}
		}
		else if (action.toLowerCase() == "onmouseover") {
			if ($(id).className != "buttonActive") {
				$(id).className = "buttonOver";
			}
		}
		else if (action.toLowerCase() == "onmouseout"){
			if ($(id).className != "buttonActive") {
				$(id).className = "buttonNormal";
			}
		}
	}
}

/**
 * Preload all mouseover images on the page and define a mouseover and mouseout
 * event for those images. All that is required is that the image has a class
 * name consisting of mouseover_* with the * being the rollover key to
 * apply to the mouseover image.
 *
 * i.e. look at the following examples to see how the class name is parsed
 *      <img class="mouseover_r" src="myimage.gif" alt=""/>
 *      out image = myimage.gif
 *      over image = myimage_r.gif
 *
 * @important! this function must be called by the onload event
 *
 * @param void
 * @return void
 *
 * @author Toby Miller <tmiller@resource.com>
 * @author Josh Zeigler <jzeigler@resource.com>
*/

function mouseoverSetup(image)
{
	// set internal vars
	var extlist = ['gif', 'jpg', 'jpeg', 'png'];
	var ext = null;
	var re = null;
	var klass = null;
	var clickklass = null;
	var key = null;
	var src = null;
	var oversrc = null;

    var init = function(el) {
        // get image source and class name
        src = el.src;
        klass = el.className;

        if (klass.contains('mouseclick_')) {
            // strip out additional classes (if they exist)
            re = new RegExp('.*(mouseclick_[a-zA-Z0-9-]+).*');
            clickklass = klass.replace(re, '$1');

            // find the supported extension
            extlist.each(function(x) {
                re = new RegExp('\\.' + x + '$');
                if (src.match(re)) {
                    ext = x;
                }
            });

            if (ext != null) {
                // get this mouseover key
                re = new RegExp('mouseclick(_[a-zA-Z0-9-]+)');
                key = clickklass.replace(re, '$1');

                re = new RegExp('\\.' + ext + '$');
                el.activesrc = src.replace(re, key + '.' + ext);

                // setup onmouseover event
                el.addEvent('click', function(){
                    this.removeEvents('mouseenter');
                    this.removeEvents('mouseleave');
                    this.setProperty('src', this.activesrc);
                });
            }
        }

        if (klass.contains('mouseover_')) {
            // strip out additional classes (if they exist)
            re = new RegExp('.*(mouseover_[a-zA-Z0-9-]+).*');
            klass = klass.replace(re, '$1');

            // find the supported extension
            extlist.each(function(x) {
                re = new RegExp('\\.' + x + '$');
                if (src.match(re)) {
                    ext = x;
                }
            });

            if (ext != null) {
                // get this mouseover key
                re = new RegExp('mouseover(_[a-zA-Z0-9-]+)');
                key = klass.replace(re, '$1');
//alert('ext=' + ext);
                if ((ext == 'png') && (document.all) && (navigator.userAgent.toUpperCase().indexOf('OPERA') < 0) && (navigator.userAgent.indexOf('MSIE 7') < 0)) {
                    // get this mouseovers over src
                    re = new RegExp('\\.' + ext + '$');
                    oversrc = src.replace(re, key + '.' + ext);

                    // get the dimensions
                    width = el.getProperty('width');
                    height = el.getProperty('height');
                    // force the spacer for transparent backgrounds
                    el.setProperty('src', _SPACER_IMAGE);

                    // setup the new properties (replace mouseovers)
                    el.overFilter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + oversrc + '\', sizingMethod=scale)';
                    el.outFilter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + src + '\', sizingMethod=scale)';

                    // apply the defaults
                    el.style.filter = el.outFilter;
                    el.style.width = width + 'px';
                    el.style.height = height + 'px';

                    // setup onmouseover event
                    el.addEvent('mouseenter', function(){
                        this.setStyle('filter', this.overFilter);
                    });

                    // setup onmouseout event
                    el.addEvent('mouseleave', function(){
                        this.setStyle('filter', this.outFilter);
                    });
                }
                else {
                    // get this mouseovers over src
                    re = new RegExp('\\.' + ext + '$');
                    oversrc = src.replace(re, key + '.' + ext);

                    // preload both over and out images
                    el.overImage = new Image();
                    el.overImage.src = oversrc;
                    el.outImage = new Image();
                    el.outImage.src = src;

//alert('oversrc=' + oversrc);
//alert('src=' + src);

                    // setup onmouseover event
                    el.addEvent('mouseenter', function(){
                    	//alert('this.overImage.src=' + this.overImage.src);
                        // I took out... messing with hompage link rollovers
                        this.setProperty('src', this.overImage.src);
                    });

                    // setup onmouseout event
                    el.addEvent('mouseleave', function(){
                        // I took out... messing with hompage link rollovers
                        this.setProperty('src', this.outImage.src);
                    });
                }
            }
        }
        else if (klass.contains('fadeover_')) {
            Global.set(new Fx.Style(el, 'opacity', {'duration': 333}), el.id);
//alert("el.id="+el.id);
            // setup onmouseover event
            el.addEvent('mouseenter', function() {
                Global.get(this.id).stop();
                Global.get(this.id).start(1);
            });

            // setup onmouseout event
            el.addEvent('mouseleave', function() {
                Global.get(this.id).stop();
                Global.get(this.id).start(0.000000000000000000000000000000000000000000000000000000001);
            });
        }

        // reset vars
        ext = null;
        re = null;
        klass = null;
        clickklass = null;
        key = null;
        src = null;
        oversrc = null;
    };

    if(image != undefined) {
        init($(image));
    }
    else {
        $$('img').each(init);
    }
}

function submitForm(frmName) {
	var frm = eval('document.' + frmName);	
	frm.submit();
	return true;
}


//on DOMReady, load up the mouse over events
window.addEvent('domready', mouseoverSetup);