/*
 * Get element by id function
 */
var vp_$;
if (!vp_$ && document.getElementById) {
    vp_$ = function () {
        var elements = new Array();
        for (var i = 0; i < arguments.length; i++) {
            var element = arguments[i];
            if (typeof element == "string") {
                element = document.getElementById(element);
            }
            if (arguments.length == 1) {
                return element;
            }
            elements.push(element);
        }
        return elements;
    };
} else {
    if (!vp_$ && document.all) {
        vp_$ = function () {
            var elements = new Array();
            for (var i = 0; i < arguments.length; i++) {
                var element = arguments[i];
                if (typeof element == "string") {
                    element = document.all[element];
                }
                if (arguments.length == 1) {
                    return element;
                }
                elements.push(element);
            }
            return elements;
        };
    }
}

/* 
 * Return true if enter key was pressed
 * @argument evt The key event
 */
function vp_isEnterKey(evt) {
    if (!evt) {
        evt = window.event;
    }
    else if (!evt.keyCode) {
        evt.keyCode = evt.which;
    }
    return (evt.keyCode == 13);
}

/* 
 * Returns true if a numeric, slash or control key was pressed
 * @argument evt The key event
 */
function vp_checkDateKey(evt) {
    return vp_validateChars(evt, "0123456789/", true);
}

/* 
 * Returns true if a numeric or control key was pressed
 * @argument evt The key event
 */
function vp_checkNumericKey(evt) {
    return vp_validateChars(evt, "0123456789", true);
}

/* 
 * Validates that a key against a list of caharacters.  Control characters are
 * always allowed.  Note - onkeypress event should be used.
 * @argument evt The key event
 * @argument strList A list of characters to validate against
 * @argument strAllow If true, then only allow what is in strList. If false,
 * then do not allow what is in strList.
 * @return True if the validation passed, false otherwise.
 */
function vp_validateChars(evt, strList, strAllow) {
    var charCode;
    if(window.event) {
        charCode = evt.keyCode; // IE
    }
    else if(evt.which) {
        charCode = evt.which; // Netscape/Firefox/Opera
    }

    var strChar = String.fromCharCode(charCode);
    if (strAllow === true) {
        // Whitelist check
        if (charCode==8 || charCode==9 || charCode==37 || charCode==39 || charCode==46 ||
            charCode==116 || (strList.indexOf(strChar)!= -1)) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        // Blacklist check
        if (charCode==8 || charCode==9 || charCode==37 || charCode==39 || charCode==46 ||
            charCode==116 || (strList.indexOf(strChar)==-1)) {
            return true;
        }
        else {
            return false;
        }
    }
}

/*
 * Error object to keep track of ajax validation errors in a form
 * @argument name The name of the error stack
 */
function _vpErrorStack(name) {
    this.form = name;
    this.errors = new Array();
}
// Set the error flag for this error to true
_vpErrorStack.prototype.setError = function(field) {
    this.errors[field] = true;
};
// Remove the error flag from the field
_vpErrorStack.prototype.clearError = function(field) {
    this.errors[field] = false;
};
// Return true if the field is set and has an error
_vpErrorStack.prototype.getError = function(field) {
    if (this.errors[field]) {
        return this.errors[field];
    }
    else {
        return false;
    }
};
// Clear all errors from the stack
_vpErrorStack.prototype.clearAll = function() {
    this.errors = new Array();
};
// Return true if the error stack has any errors
_vpErrorStack.prototype.hasErrors = function() {
    var flag = false;
    for(var i in this.errors) {
        if (this.errors[i] === true) {
            flag = true;
            break;
        }
    }
    return flag;
};

// Functions to determine window height and width
getViewportWidth = function() {
  var width = 0;
  if (document.documentElement && document.documentElement.clientWidth) {
    width = document.documentElement.clientWidth;
  }
  else if (document.body && document.body.clientWidth) {
    width = document.body.clientWidth;
  }
  else if (window.innerWidth) {
    width = window.innerWidth - 18;
  }
  return width;
};

getViewportHeight = function() {
  var height = 0;
  if (document.documentElement && document.documentElement.clientHeight) {
    height = document.documentElement.clientHeight;
  }
  else if (document.body && document.body.clientHeight) {
    height = document.body.clientHeight;
  }
  else if (window.innerHeight) {
    height = window.innerHeight - 18;
  }
  return height;
};

/*
 * Loading Message - Displays/Hides contents
 * @argument showLoad boolean
 * @argument type The delay scenario
 * @argument name Dynamic info
 */
function vp_loader(showLoad, type, name) {
    // Close any overlays
	vp_closeOverlayPage();
    
    if (vp_$("rLoadMsg") || vp_$("wLoadMsg")) {
        if (showLoad) {
            // Set shade size & show
            $("#shade").css({width:getViewportWidth() + "px", height:document.body.scrollHeight + 20 + "px", left:"0"});
            // Show loading message
            if (vp_$("wLoadMsg")) {$("#wLoadMsg").css("visibility", "visible");}
            else {
	            if (type == "search") {$("#loadMsg").html("Searching For Coupons...");}
                else if (type == "reload") {$("#loadMsg").html("Refreshing Your Content...");}
	            else if (type == "bpp") {$("#loadMsg").html("Loading Business Profile...");}
	            else if (type == "cat") {$("#loadMsg").html("Loading Coupons for " + name + "...");}
	            else {$("#loadMsg").html("Please Wait...");}
	            
	            $("#rLoadMsg").show();
	            $("#statusMsg").hide();
	            $(".statusMsg").hide();
	            $("#sortForm").hide();
	            vp_hideMessage();
	            
	            if ($(".bto")) {$(".bto").hide();}
	            if ($(".bppCat")) {$(".bppCat").hide();}
	        }
        } else {
            $("#shade").css("left", "-5000px");
            $("#rLoadMsg").hide();
            $("#statusMsg").show();
            $(".statusMsg").show();
        }
    }
}

/*
 * Controls the display of super category tabs. 
 * @argument filter The name of the filter ('supercat' or '' for all)
 * @argument value The value of the filter
 * @argument state The mouse state - click, over or out
 */
function vp_catTab(value, state) {
	if (value == "") {value = "More";}
	if (state == "over") {
	    $("#img" + value).attr("src", "/7/img/cat/tab"+value+"Over.gif");
	}
	else if (state == "out") {
	    $("#img" + value).attr("src", "/7/img/cat/tab"+value+".gif");
	}
}

/* 
 * Remove leading and trailing spaces from a string
 * @argument str The string to trim
 * @return The trimmed string
 */ 
function vp_trimStr(str) {
    if (str.charAt(0) == " ") {
        str = vp_trimStr(str.substring(1));
    }
    if (str.charAt(str.length-1) == " ") {
        str = vp_trimStr(str.substring(0,str.length-1));
    }
    return str;
}

/* 
 * Validate that a required field is not empty
 * @argument field The id of the field
 * @argument errorDiv The id of the error div (for error messages)
 * @argument fieldName The name of the field to appear in the error message
 */ 
function vp_validateEmpty(field, errorDiv, fieldName) {
    var str = vp_trimStr($("#" + field).val());
    if ((str === null) || (str.length === 0)) {
        $("#" + errorDiv).html(fieldName + " required");
    }
    else {
        $("#" + errorDiv).html("");
    }
}

/* 
 * Window Formatting
 * defaults: width-650px height-450px window name-win
 */
function vp_openWindow(path,winName,w,h)
{
	window.name="parentWindow";
	if (w == null) {w = 650;} if (h == null) {h = 450;} if (winName == null) {winName = 'win';}
	msgWindow=window.open(path,winName,"menubar=yes,width="+w+",height="+h+",resizable=yes,toolbar=no,scrollbars=yes,status=yes,screenX=50,screenY=50");
	if (msgWindow != null) {msgWindow.focus();}
}
//Image Window Formatting
function vp_openImgWindow(path,winName,w,h)
{
	window.name="parentWindow";
	if (w == null) {w = 650;} if (h == null) {h = 450;} if (winName == null) {winName = 'win';}
	msgWindow=window.open(path,winName,"menubar=no,width="+w+",height="+h+",resizable=yes,toolbar=no,scrollbars=yes,status=yes,screenX=50,screenY=50");
	if (msgWindow != null) {msgWindow.focus();}
}
//CouponLink Window Formatting
function vp_couponLink(path,winName,w,h, zoneMapId)
{
	window.name="parentWindow";
	if (w == null) {w = 650;} if (h == null) {h = 450;} if (winName == null) {winName = 'win';}
	msgWindow=window.open(path,winName,"menubar=yes,width="+w+",height="+h+",resizable=yes,toolbar=yes,scrollbars=yes,status=yes,screenX=50,screenY=50");
	if (msgWindow != null) {msgWindow.focus();}
}
//Open link in parent window and close the child window
function vp_updateParent(newURL) {
	opener.parent.location=newURL;
	window.close();
}

/* 
 * Resize an iFrame after it loads
 * @argument iframeWindow The iFrame to resize
 */
function adjustIFrameSize(iframeWindow) {
	if (iframeWindow.document.height) {
		var iframeElement = document.getElementById(iframeWindow.name);
		iframeElement.style.height = iframeWindow.document.height + 'px';
		iframeElement.style.width = iframeWindow.document.width + 'px';
	}
	else if (document.all) {
		var iframeElement = document.all[iframeWindow.name];
		if (iframeWindow.document.compatMode && iframeWindow.document.compatMode != 'BackCompat') {
			iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 5 + 'px';
			iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth + 5 + 'px';
		}
		else {
			iframeElement.style.height = iframeWindow.document.body.scrollHeight + 5 + 'px';
			iframeElement.style.width = iframeWindow.document.body.scrollWidth + 5 + 'px';
		}
	}
}

/* 
 * Determine the mouse position
 * @argument e The event
 * @argument xy The horiz or vert position to return
 * @return The position (x or y)
 */
function vp_mousePosition(e,xy) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) {
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) {
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	if (xy == 'x') return posx;
	else return posy;
}

/* 
 * Date formatter
 * @argument format The requested date format
 */
function vp_dateFormat(format) {
	var date = new Date();
	
	// MMddyymmss format
	var time = date.getTime();
	
	// M/yyyy format
    var M = date.getMonth() + 1;
    var yyyy = date.getYear() + "";
    if (yyyy.length < 4) {
    	yyyy=""+(yyyy-0+1900);
    }
    var Myyyy = M + "/" + yyyy;
    
    if (format == "MMddyymmss") {return time}
    if (format == "M/yyyy") {return Myyyy}
}

/* 
 * Textarea Limit Validation
 * @argument field The text area field
 * @argument countfield The counter field
 * @argument maxlimit The max allowable characters
 */
function vp_textCounter(field, countfield, maxlimit) {
    if (field.value.length > maxlimit) {
        field.value = field.value.substring(0, maxlimit);
    }
    else {
        countfield.value = maxlimit - field.value.length;
    }
}

/* 
 * Stylesheet switcher
 * @argument title The title of the stylesheet(s) to activate
 */
function vp_setStyleSheet(title) {
	if (title == "Site") {$("#couponSS").attr("href", "/7/css/empty.css");}
	else {$("#couponSS").attr("href", "/7/css/coupon.css");}
	
	$("#printSS").attr("href", "/7/css/print" +title+ ".css");
}

/* 
 * Create and set a cookie
 * @name The name of the cookie
 * @value The value of the cookie
 * @days Expiration days (optional) 
 */
function vp_createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

/* 
 * Return the contents of a cookie or null if not found
 * @name The name of the cookie
 */
function vp_readCookie(name) {
    var ca = document.cookie.split(';');
    var nameEQ = name + "=";
    
    for(var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length); //delete spaces
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    
    return null;
}

/* 
 * Remove a cookie
 * @name The name of the cookie
 */
function vp_clearCookie(name) {
  vp_createCookie(name, "", -1);
}

// Set/Clear status messages
function vp_setStat() {
	window.status = this.title;
	if (!_vpLogger.debugEnabled) return true;
}
function vp_clearStat() {window.status = ""}

// Initial Caps
function changeCase(str, trim) {
	var index, tmpStr, tmpChar, preString, postString, strlen;
	tmpStr = str.toLowerCase();
	strLen = tmpStr.length;
	
	// trim an "s"
	if (trim == "true") {
		lastChar = tmpStr.substring(strLen-1, strLen);
		if (lastChar == "s") {tmpStr=tmpStr.replace(/.$/,'');}
	}
	
	if (strLen > 0) {
		for (index = 0; index < strLen; index++) {
			if (index == 0) {
				tmpChar = tmpStr.substring(0,1).toUpperCase();
				postString = tmpStr.substring(1,strLen);
				tmpStr = tmpChar + postString;
			}
			else {
				tmpChar = tmpStr.substring(index, index+1);
				if (tmpChar == " " && index < (strLen-1)) {
					tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
					preString = tmpStr.substring(0, index+1);
					postString = tmpStr.substring(index+2,strLen);
					tmpStr = preString + tmpChar + postString;
	         	}
	      	}
	   	}
	}
	str = tmpStr;
	return str;
}

/* 
 * Initial cap first letter of each word
 * @argument str The str to convert
 */
function cnvrt2Upper(str) {
	function cnvrt() {
		return arguments[0].toUpperCase();
	}
	return str.toLowerCase().replace(/\b[a-z]/g, cnvrt);
}

/* 
 * Show/hide layers
 */
function vp_toggle(objectID, picID, d) {
    var obj = vp_$(objectID).style;
    if (obj.display == "block") {
        obj.display = "none";
        if (picID != null)
            {vp_$(picID).src = "/7/img/closed.gif";}
    }
    else {
        obj.display = "block";
        if (picID != null) {
            if (d == "up") {vp_$(picID).src = "/7/img/openup.gif";}
            if (d == "down") {vp_$(picID).src = "/7/img/opendown.gif";}
        }
    }
}

/* 
 * Toggle offer details
 */
function vp_toggleDetails(objID, picID, page) {
	if ($("#" +objID+ "1").is(":hidden")) {
		$("#" +objID+ "1").slideDown("slow");
		$("#" +objID+ "2").slideDown("slow");
		$("#" +objID+ "3").slideDown("slow");
		// arrow img
		$("#" +picID+ "1").attr("src","/7/img/opendown"+page+".gif");
		$("#" +picID+ "2").attr("src","/7/img/opendown"+page+".gif");
		$("#" +picID+ "3").attr("src","/7/img/opendown"+page+".gif");
	} else {
		$("#" +objID+ "1").slideUp("fast");
		$("#" +objID+ "2").slideUp("fast");
		$("#" +objID+ "3").slideUp("fast");
		// arrow img
		$("#" +picID+ "1").attr("src","/7/img/closed"+page+".gif");
		$("#" +picID+ "2").attr("src","/7/img/closed"+page+".gif");
		$("#" +picID+ "3").attr("src","/7/img/closed"+page+".gif");
	}
}

//Misc. functions
function vp_emailTo(path) {
    document.location=path;
}
function vp_noDaughter(path) {
    window.location=path
}
function vp_trackSorting(url) {
    document["TRACKER"].src = url;
}

// Valpak.com Tour
var openedWin = null;
var wpercent = 100;

function launch() {
	var args = launch.arguments
	var url = args[0]
	var width = args[1]
	var height = args[2]
	
	if (!url || !width || !height) {
		alert("Error");
	} else {
		var scr_w = screen.availWidth
		var scr_h = screen.availHeight
		var target_w = 0
		var target_h = 0
		wpercent = 100

		if (width >= scr_w || height >= scr_h) {
			if ((width+8) >= (height+27)) {
				target_w = scr_w - 8	//target width is screen width - 8
				wpercent = Math.floor((target_w * 100)/width) //get percentage scaled down
				target_h = Math.floor((height * wpercent)/100) - 27 //scale height to  percentage then subtract standard title bar height
				wpercent = Math.floor((target_h * 100)/height)	//re-adjust percentage
				target_w = Math.floor((width * wpercent)/100)	//scale width to new percentage
				width = target_w
				height = target_h
			}
			else if ((height+27) > (width+8)) {
				target_h = scr_h - 27
				wpercent = Math.floor((target_h * 100)/height)
				target_w = Math.floor((width * wpercent)/100) - 8
				wpercent = Math.floor((target_w * 100)/width)
				target_h = Math.floor((height * wpercent)/100)
				width = target_w
				height = target_h
			}
		}
		_launch(url, width, height, args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
	}
}

function _launch() {
	closeChild()
	
	var args = _launch.arguments
	var url = args[0]
	var width = args[1]
	var height = args[2]
	var resizable = args[3] ? "yes" : "no"
	var scrollbars = args[4] ? "yes" : "no"
	var toolbar = args[5] ? "yes" : "no"
	var menubar = args[6] ? "yes" : "no"
	var status = args[7] ? "yes" : "no"
	var address = args[8] ? "yes" : "no"
	var directories = args[9] ? "yes" : "no"
	
	var NewX = Math.max(0, Math.floor((screen.availWidth-(width+8))/2));
	var NewY = Math.max(0, Math.floor((screen.availHeight-(height+27))/2));
	
	var params = ''
	
	params += "width="+width // 1
	params += ",height="+height // 2
	params += ",screenx="+NewX
	params += ",screeny="+NewY
	params += ",left="+NewX
	params += ",top="+NewY
	params += ",resizable="+resizable // 3
	params += ",scrollbars="+scrollbars // 4
	params += ",toolbar="+toolbar // 5
	params += ",menubar="+menubar // 6
	params += ",status="+status // 7
	params += ",location="+address // 8
	params += ",directories="+directories // 9
	
	openedWin = window.open(url, "demodashboard", params);
}

function closeChild() {
	if (openedWin != null) {
		if (!openedWin.closed) {
			openedWin.close();
		}
	}
}
onunload = closeChild;
