$(document).ready(function(){
	var dimensions = screenDimensions(),
		siteMode = "development";

	// Find screen size
	calibrator();
	
	// Identify Browser and store screen size
	$("body").data("browser", navigator.appName)
		.data("screen", {width: dimensions[0], height: dimensions[1]});
	
	marqueeBuilder();
	
	actors();
	
	// Emulate clicking the first button and starting the show
	$("body").data("showsOn", 0).data("play", "yes");
	buttonClick($(".button0"), "play");
	displayTimer(4500);

	$("#prepage-widget").css("zIndex", "1");
	
	// Apply auto centering elements specified
	
	centerator();
	/*$(".footerbackground").css({
		"bottom": "603px",
		"position":"relative"
	});*/
	
	/* IE7 Fixes */
	if ($.browser.msie) {
		if ($.browser.version == '7.0') {
			$("body").css("maxWidth", "976px");
		}
	}
});

/*
	Custom functions for this site
*/
function actors(){
	$("h6").live("click", function(e){
		switch ($(this).text()) {
			case "pause":
				clearTimeout(t);
				$(this).text("play");
				break;
			case "play":
				$(this).text("pause");
				displayTimer(4500);
				break;
		}
	});
		
	// CLICK on a button
	$(".twoShow [class*='button']").live("click", function() {	
		window.location = $(this).attr("alt");
		buttonClick($(this), "don't play");
	});
	
	buttonHoverEvents();
}
function redirectPage(link) {
	window.location = link;
}
function marqueeBuilder() {
	// Create the marquee bin
	addElements(1, "div", ".swbanner", "oneShow marqueeBin");
	
	// Add play and pause actor
	//addElements(1, "h6", ".marqueeBin", "sevenShow showAction layerOne", "pause");
	
	// Add panesBin to the marquee
	addElements(1, "div", ".marqueeBin", "fourShow panesBin");
	// Add buttonsBin to the marquee
	addElements(1, "div", ".marqueeBin", "twoShow buttonBin");

	// Add buttons(image) to $(".buttonBin")
	for (var i=1; i<5; i++) {
		//Pane Links
		if (i == 1) {
			var link = 'http://shop.vh1.com/Mob-Wives-Season-1-Uncensored/A/B0061U2QRS.htm';
			var header = 'Mob Wives DVD';
			var subheader = 'Buy Season One Now!';
		}
		else if (i == 2) {
			var link = 'http://shop.vh1.com/Mob-Daughter-The-Mafia-Sammy-The/A/1250003059.htm';
			var header = 'MobDaughter';
			var subheader = 'Pre-order your copy today of this must-read!';
		}
		else if (i == 3) {
		var link = 'http://shop.vh1.com/category/68822803121/1/Apparel.htm';
			var header = 'NEW That Metal Show T-Shirt';
			var subheader = '"Rock on" with this t-shirt from the ONLY rock and heavy metal show on TV!';
		}
		else if (i == 4) {
			var link = 'http://shop.vh1.com/category/71567409401/1/National-Metal-Day.htm';
			var header = 'National Metal Day T-shirts';
			var subheader = 'Let eveyone know that you are all Metal with this tee!';
		}
		
		// Images are stored as button0.png, button1.png, etc...easier this way
		$(".buttonBin").append("<img id='"+i+"' src='http://vh1.amazonwebstore.com/images/vh1_marquee_button"+i+".jpg' class='threeShow button"+i+"' style='border:3px solid #ffffff;' alt='" + link + "'>");
		// For each button added, add corresponding view pane > $(".pane"+i)
		addElements(1, "div", ".panesBin", "fiveShow pane"+i, "\
			<div class='eightShow'>\
				<div class='tenShow'>\
					<div class='elevenShow'><a href='" + link + "'>" + header + "</a></div>\
					<div class='twelveShow'>" + subheader + "</div>\
					<div class='thirteenShow'><a href='" + link + "'>Order Now</a></div>\
				</div>\
				<div class='tenShowBg'></div>\
				<a href='" + link + "'><img src='http://vh1.amazonwebstore.com/images/vh1_marquee_pane"+i+".jpg' class='sixShow paneImage"+i+"' style='width:635px; height:415px; z-index:1; position:relative;'></a>\
			</div>\
		");
		$(".pane1").fadeIn(600);
		$(".buttonBin").fadeIn(600);
		$(".buttonBin img#1").css("border", "3px solid #008aff");
	};	
	
	// Resize $(.panesBin) to have a width that is its width times the number of panes (scrollable setup)
	$(".panesBin").data("css", {
			width: ruler($(".panesBin"), "width"), 
			height: 415
		})
		.css("width", $(".panesBin").data("css").width)
		.children("[class*='pane']").css({
			"width":$(".panesBin").data("css").width,
			"height":$(".panesBin").data("css").height
		});
}

function buttonHoverEvents() {
	// HOVER over a button
	$("[class*='threeShow']").live("mouseover", function() {
		$(this).css("border", "3px solid #008aff");
		// Fade in the pane matching this ID while simultaneously fading out siblings
		$(".pane"+$(this).attr("id")).fadeIn(600).siblings().fadeOut(600);
		$(this).data("action", "clicked")
			.css("border", "3px solid #008aff")
			// Change action data to unclicked for the sibling buttons so they have hover action
			.siblings("[class*='button']").data("action", "unclicked")
			.css("border", "3px solid #ffffff");
		clearTimeout(t);
		$(".showAction").text("play");
		//alert($("body").data("showsOn"));
	});
	
	// HOVER off a button
	$("[class*='threeShow']").live("mouseout", function() {
		//$(this).css("border", "3px solid #ffffff");
		$(".showAction").text("play");
		clearTimeout(t);
		var pane = parseInt($(this).attr("id")) + 1;
		//alert(pane);
		displayTimer(4500, pane);
	});
}

// Animate top position by value passed in on movement
function buttonMover(thisObject, movement) {
	switch($(thisObject).data("action")) {
		case "clicked":
			$(thisObject).siblings().stop().animate({top:"0px"}, 300);
			break;
		case "unclicked":
			$(thisObject).stop().animate({top:movement}, 300);
			break;
	}
}

function buttonClick(thisObject, showAction) {
	// Store click reference so hovering doesn't reset top position
	
	$(thisObject).data("action", "clicked")
		.css("border", "3px solid #008aff")
		// Change action data to unclicked for the sibling buttons so they have hover action
		.siblings("[class*='button']").data("action", "unclicked")
		.css("border", "3px solid #ffffff");
	
	// If the slide show is not suppose to continue playing
	if (showAction=="don't play") {
		// Pause slide show by clearing "t" which represents the timeout between slides
		clearTimeout(t);
		$(".showAction").text("play");
	}

	// Fade in the pane matching this ID while simultaneously fading out siblings
	$(".pane"+$(thisObject).attr("id")).fadeIn(600).siblings().fadeOut(600);
}

// Advances the pane every "duration" (seconds)
function displayTimer(duration, startpane) {
	t=setTimeout(function() {
		if (startpane != null) {
			$("body").data("showsOn", startpane);
		}
		else {
			// If the show is not on the last pane
			if ($("body").data("showsOn") < 4) {
				// Increment the show count by 1
				$("body").data("showsOn", $("body").data("showsOn") + 1);
			}
			else {
				// Otherwise reset the show count to 0
				$("body").data("showsOn", 0);
			}
		}
		// Emulate button click with modified show count
		buttonClick($(".button"+$("body").data("showsOn")));
		displayTimer(duration);
	}, duration);
}

/*
	theFrame Core > frame.js
*/

function screenDimensions() {
	if (typeof(window.innerWidth) == 'number') {
		//Non-IE
		screenWidth = window.innerWidth;
		screenHeight = window.innerHeight;
	}
	else 
		if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
			//IE 6+ in 'standards compliant mode'
			screenWidth = document.documentElement.clientWidth;
			screenHeight = document.documentElement.clientHeight;
		}
		else 
			if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
				//IE 4
				screenWidth = document.body.clientWidth;
				screenHeight = document.body.clientHeight;
			}
	var screenDimensions=new Array(screenWidth, screenHeight);
	return screenDimensions;
}

/* 1. Quantity  2. Element Type 3. Parent Class (whom new elements will be children of) 4. New Element Class 5. HTML content */
function addElements(howMany, elementType, parentClass, className, theHtml, theAlt, theInputType, theInputValue) {
	var i = howMany, 
    		fragment = document.createDocumentFragment(), 
    		div = document.createElement(elementType);
	while (i--) {
	    $(fragment.appendChild(div.cloneNode(true))).addClass(className).html(theHtml);
	}
	$(parentClass).append(fragment); 
}

// Find pixel measurements without using parseInt
function ruler(thisObject, attr) {
	if (attr="width") {
		if ($("body").data("browser")=="Microsoft Internet Explorer") {
			var thisSize = $(thisObject).width();
			return thisSize*1;
		} else {
			var thisSize = $(thisObject).css(attr).split("px");
			return thisSize[0]*1;
		}
	} else {
		var thisSize = $(thisObject).css(attr).split("px");
		return thisSize[0]*1;
	}
}

// Top and Left CSS Positions
function positionFinder(thisObject, attr) {
	var p = $(thisObject),
		position = p.position();
	switch(attr) {
		case "top":
			return [position.top]; 
			break;
		case "left":
			return [position.left]; 
			break;
	}	
}

function fadeAndRemove(thisObject) {
	$(thisObject).fadeOut(300, function() {
		$(thisObject).remove();
	});
}

function slideAndRemove(thisObject) {
	$(thisObject).slideUp(300, function() {
		$(thisObject).remove();
	});
}

/* BIG INPUT: screenHeight, screenWidth, prompt, input value, button text*/
function overlayInput(screenHeight, screenWidth, formID, prompt, inputLabel, buttonText) {
	$(".eight").css("height", screenHeight).addClass("layerTwo").fadeIn(500);
	switch(formID) {
		case "loading":
			$(".nine").css({
					"top": Math.floor((screenHeight/2)-60),
					"left": Math.floor((screenWidth)*.10)
			})
			.children("input").hide()
			.siblings(".twentytwo").css({
				"textAlign": "center",
				"width": "100%"
			}).html("Loading Lesson Book<br><img src='/html/cupertino/images/bigspinner.gif'>")
			.siblings("h6").hide();
			break;
		default:
			$(".nine").css({
					"top": Math.floor((screenHeight/2)-60),
					"left": Math.floor((screenWidth)*.10)
				})
				.children("input").show().val(prompt)
				.siblings(".twentytwo").removeAttr("style").show().text(inputLabel)
				.siblings("h6").show().text(buttonText).attr("alt", formID);
			}
}

var dateFormat = function () {
	var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

/*
BREAK: frame.js
*/
/*
	frame.spacial.js > Custom functions for this site
*/

// Pull out 20 from 20Percent and convert to number
function autoDistributor() {
	calibrator();
	storeAttributes();
	applyDimensions();
	renderingCorrector();
}

function findPercentage(thisObject){
	var classArray = $(thisObject).attr("class").split(" "),
		percentage = 0;
	$.each(classArray, function(){
		switch (this.substring(2)) {
			case "percent":
				percentage += (this.substring(0,2)*1)/100;
				break;
			default:
				
				break;
		}
	});
	return percentage;
}

// Meat and taters
function applyDimensions(){
	$("div, h5, h6").each(function() {		
		var parentsWidth = $(this).parent().css("width").split("px"),
			parentsWidth = parentsWidth[0];

		if ($(this).data("attributes").percent>0) {		
			$(this).css("width", parentsWidth*$(this).data("attributes").percent);
		} else {
			var remainder = 1;
			$(this).siblings("[class*='percent']").each(function() {	
				remainder -= findPercentage($(this));	
			});	
			$(this).css("width", parentsWidth*(remainder/$(this).data("attributes").siblingsUndefined));
		}

		if ($(this).data("attributes").siblings>1) {
			$(this).addClass("float_left");
		} else {}
		offsetCalculator($(this));
	});
}

function renderingCorrector() {
	// Sub-pixel Rendering workaround. 
	$("div, h5, h6").each(function() {
		if ($(this).data("attributes").children>0) {
			var firstChild = $(this).children(":first"),
				firstPosition = firstChild.position(), 
				lastChild = $(this).children(":last"),
				lastPosition = lastChild.position();		
			
			// First check for top values (first to last). Don't match, class="right"
			if (firstPosition.top!=lastPosition.top) {
				$(lastChild).removeClass("float_left").addClass("right").parent().addClass("relative");
			} else {}
		} else {}
	});
}
// Make each element aware of its situation: "I'm Michael and I have 3 brothers. My parents name is Jim."
function storeAttributes() {
	$("div, h5, h6").each(function() {
		$(this).data("attributes", { 
			children: $(this).children().length,
			siblings: $(this).parent().children().length,
			siblingsDefined:$(this).parent().children("[class*='percent']").length,
			siblingsUndefined:$(this).parent().children().length-$(this).siblings("[class*='percent']").length,
			percent: findPercentage($(this)),
			remainder:0
		});
	});	
}

function calibrator() {
	var dimensions = screenDimensions();
	$(".screenWidth").css("width", dimensions[0]);
	$(".screenHeight").css("height", dimensions[1]);
	$(".screenAll, body").css({
		"maxWidth":dimensions[0]
	});
	if ($.browser.msie) {
		if ($.browser.version == '7.0') {
			$(".screenAll, body").css({
				"width":dimensions[0]
			});
		}
	}
}

function centerator() {
	$(".centerAcross").each(function() {
		$(this).css({
			"position": "relative",
			"left": (parseInt($(this).parent().css("width"))-parseInt($(this).css("width")))/2
		});
	});

	$(".centerDown").each(function() {
		$(this).css({
			"position": "relative",
			"top": (parseInt($(this).parent().css("height"))-parseInt($(this).css("height")))/2
		});
	});
	
	$(".centerAll").each(function() {
		$(this).css({
			"position": "relative",
			"top": (parseInt($(this).parent().css("height"))-parseInt($(this).css("height")))/2,
			"left": (parseInt($(this).parent().css("width"))-parseInt($(this).css("width")))/2
		});
	});
}

// calculates total increase(offset) to width caused by padding and margins add border
function offsetCalculator(thisObject) {
	var attributeTypes = ["padding", "margin", "border", "height", "width"],
		attributeArray = new Array(),
		computedWidthOffset = 0, computedHeightOffset = 0;
	$.each(attributeTypes, function() {
		attributeArray = attributeArray.concat(attributeCalculator(thisObject, this.toString()));
	});
	for (var i=0; i<attributeArray.length-2; i++) {
		var thisValue = attributeArray[i],
			thisValue = thisValue.substring(0, thisValue.length-2)*1;
		switch(isOdd(i)) {
			case true:	
				computedWidthOffset += thisValue;	
				break;
			case false:
				computedHeightOffset += thisValue;	
				break;
		}
	};
	$(thisObject).css({
		"width": makeNumber(attributeArray[attributeArray.length-1], 2)-computedWidthOffset+"px",
		"height": makeNumber(attributeArray[attributeArray.length-2], 2)-computedHeightOffset+"px"
	});
}

// calculated individual attributes, specializes in things with multiple attributes
function attributeCalculator(thisObject, attribute) {
	var attributeArray = new Array();
	switch(attribute) {
		case "padding": case "margin": 
			var orientations = ["top", "right", "bottom", "left"];
			$.each(orientations, function(i) {
				attributeArray.push($(thisObject).css(attribute + "-" + orientations[i]));
			});
			break;
		case "border":
			var orientations = ["top-width", "right-width", "bottom-width", "left-width"];
			$.each(orientations, function(i) {
				attributeArray.push($(thisObject).css(attribute + "-" + orientations[i]));
			});
			break;
		case "height": case "width": default:
			attributeArray.push($(thisObject).css(attribute));
			break;
	}	
	return attributeArray;
}

/*
	end of frame.spacial.js
*/





