var d = document;

String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
}

$(document).ready(function() {
	init();
	customizeAdmin();
	buildProductNav();
});

customizeAdmin = function() {
	var t = $("#edit-menu-title");
	var l = $("#edit-localizernode-locale");
	if (l.size()) {
		if (l.val() != "-" && l.val() != "en") {
			// disable language selector when translating a node
			l.attr("disabled", "disabled");
			if (t.size()) {
				// hide menu settings fieldset when translating a node
				t.parents("fieldset").hide();
			};
		};
	};
	
	// fix "insert image or link" on resource library edit form
	/*var imceRebind = false;
	l = $('edit-field-static-path-0-value-IMCE-image');
	if (l.length) {
		//l = $(l);
		l.hide();
		l = l.parent();
		t = l.html().replace(/\sor\s/i, "");
		l.html(t);
		imceRebind = true;
	};
	
	l = $('edit-field-thumbnail-0-value-IMCE-link');
	if (l.length) {
		//l = $(l);
		l.hide();
		l = l.parent();
		t = l.html().replace(/\sor\s/i, "");
		l.html(t);
		imceRebind = true;
	};
	
	if (imceRebind) {
		ii.initiate(); // rebind IMCE events
	};*/
	
	// hook into node form submit event
	$("#node-form").bind("submit", function() {
		// move the content from tinyMCE into the form so we can clean it
		if (typeof tinyMCE != "undefined") {
			tinyMCE.triggerSave();
		};
		
		// remove unwanted div IDs from content
		$("#edit-field-aux-content-0-value, #edit-body, #edit-field-feature-1-0-value, #edit-field-feature-2-0-value, #edit-field-feature-3-0-value")
			.each(function() {
				var v = $(this).val();
				if (v) {
					v = v.replace(/^\s*<div\s+id="(col-(right|left|full)|featured|news(1|2|3))"[^>]*>/gi, "<div>");
					$(this).val(v);
				};
			});
	});
};



buildProductNav = function() {
	var group = $("#block-slicedmenu-2").hide();
	var type = $("#block-slicedmenu-3").hide();
	var model = $("#block-slicedmenu-4").hide();
	if (group.size()) {
		var prodnav = $("<form>")
			.insertBefore(group)
			.wrap('<div id="nav-product"></div>')
			.before(getFunFact())
			.wrap("<div></div>");
		buildSelect(prodnav[0], group, "groupselect", tstrings.selgroup, true);
		buildSelect(prodnav[0], type, "typeselect", tstrings.seltype);
		buildSelect(prodnav[0], model, "modelselect", tstrings.selmodel);
	};
};

buildSelect = function(container, src, id, val, pluckfirst) {
	var srclinks = src.find("a");
	if (srclinks.size()) {
		var srcselect = document.createElement("select");
		srcselect.id = id;
		container.appendChild(srcselect);
		srcselect.options[0] = new Option(val, "");
		srcselect = $("#" + id).bind("change", function() {
			if (this.value) {
				location.href = this.value;
			};
		});
		if (src.size()) {
			srclinks.each(function(i) {
				var srclink = $(this);
				if (pluckfirst && i == 0) {
					$('<p class="viewall"><a href="' + srclink.attr("href") + '">' + srclink.html() + '</a></p>').insertAfter($(container));
				} else {
					srcselect[0].options[((pluckfirst) ? i : i + 1)] = new Option("", srclink.attr("href"));
			      	srcselect[0].options[((pluckfirst) ? i : i + 1)].innerHTML = srclink.html(); // needed to preserve HTML entities
			      	if (srclink.parent().attr("class") == "active") {
			      		srcselect[0].options[((pluckfirst) ? i : i + 1)].selected = "selected";
			  		};
	  			};
			});
		};
	};
	src.remove();
};

getFunFact = function() {
	return $("#funfact")[0] || '<p id="funfact"><span></span></p>';
}

// load stylesheet for js-enabled browsers
if(d.getElementById && d.createTextNode) {
	d.getElementsByTagName("html")[0].className = "js";
};

init = function() {
	if(d.getElementById && d.createTextNode) {
		// remove caret image from nav subheaders
		$("#navigation .menuheader").parent().css("background", "none").css("margin-left", "-13px");
		
		for(var i=0; t=d.getElementsByTagName("input")[i]; i++) {
			var tt = t.getAttribute("type");
			if(tt == "text") {
				// apply class to text elements
				t.className = (t.className == "") ? "text" : t.className + " text";
			} else if(tt == "button" || tt == "submit") {
				// apply class to button elements
				t.className = (t.className == "") ? "button" : t.className + " button";
			} else if(tt == "image") {
				// apply class to image elements
				t.className = (t.className == "") ? "image" : t.className + " image";
			};
		};
		// attach events to search form
		var l = d.getElementById("txtSearch");
		if(l) {
			l.onfocus = function() {if(l.value == tstrings.searchsite) l.value = ""};
			l.onblur = function() {if(l.value.trim() == "") l.value = tstrings.searchsite};
		};
		// attach events to font-controls
		a = d.getElementById("font-smaller").firstChild;
		if(a) {
			a.onclick = function() {reduceFontSize(); this.blur(); return false};
			a.onkeypress = function() {reduceFontSize(); return false};
		};
		a = d.getElementById("font-larger").firstChild;
		if(a) {
			a.onclick = function() {increaseFontSize(); this.blur(); return false};
			a.onkeypress = function() {increaseFontSize(); return false};
		};
		// attach events to help menu (formerly IE only)
		toggleHelpOn = function() {
			d.getElementById("help").className = "over";
		};
		toggleHelpOff = function() {
			d.getElementById("help").className = "";
		};
		// apply odd/even classes to add to cart table rows
		var t = d.getElementsByTagName("TABLE");
		if(t) {
			for(var i=0; i<t.length; i++) {
				if(t[i].className == "add-to-cart" || t[i].className == "partner-profile") {
					var tb = t[i].getElementsByTagName("TBODY")[0];
					for(var j=0; (tr = tb.getElementsByTagName("TR")[j]); j++) {
						if(tr.className == "") {
							if(j % 2) {
								tr.className = "odd";
							} else {
								tr.className = "even";
							};
						};
					};
				};
			};
		};
	};
	setStyles();
};

setActiveStyleSheet = function(title) {
	if(d.getElementById && d.createTextNode) {
		var i, a = d.getElementsByTagName("link"), l = a.length;
		for(i=0; i < l; i++) {
			if(a[i].getAttribute("rel").indexOf("style") != -1 && a[i].getAttribute("title")) {
				if(a[i].getAttribute("title") == title) {
					a[i].disabled = false;
				} else {
					a[i].disabled = true;
				};
			};
		};
	};
};

setStyles = function() {
	var cookie = readCookie("armStyles");
	var title = cookie ? cookie : "small";
	createCookie("armStyles", title, 365);
	setActiveStyleSheet(title);
};

reduceFontSize = function() {
	var fs = readCookie("armStyles");
	switch(fs) {
		case "small":
			// do nothing
			break;
		case "medium":
			fs = "small";
			break;
		case "large":
			fs = "medium";
			break;
		case "x-large":
			fs = "large";
			break;
		default:
			fs = "small";
	};
	createCookie("armStyles", fs, 365);
	setActiveStyleSheet(fs);
};

increaseFontSize = function() {
	var fs = readCookie("armStyles");
	switch(fs) {
		case "small":
			fs = "medium";
			break;
		case "medium":
			fs = "large";
			break;
		case "large":
			fs = "x-large";
			break;
		case "x-large":
			// do nothing
			break;
		default:
			fs = "medium";
	};
	createCookie("armStyles", fs, 365);
	setActiveStyleSheet(fs);
};

createCookie = function(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  } else {
  	expires = "";
  };
  d.cookie = name+"="+value+expires+"; path=/";
};

readCookie = function(name) {
  var nameEQ = name + "=";
  var ca = d.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  };
  return null;
};

function popUpWindow(URL,windowName,width,height) {
	var w = screen.availWidth;
	var h = screen.availHeight;
	var leftPos = Math.round((w-width)/2);
	var topPos = Math.round((h-height)/2);
	var msgWindow = window.open(URL,windowName,"top="+topPos+",left="+leftPos+",width="+width+",height="+height+",scrollbars,resizable");
	msgWindow.focus();
};

parseQuery = function() {
	var returnVals = new Array();
	qString = new String(window.location);
	var queryStart = qString.indexOf('?');
	if (queryStart==-1) {
		return returnVals;
	};
	var query = qString.substring(queryStart + 1, qString.length);
	var parts = query.split("&");
	for (var i=0; i<parts.length; i++) {
		bits = parts[i].split("=");
		if(bits[1]) {
			subbits = bits[1].split("#"); // added by T.D. to handle fragment identifier in URL
			returnVals[bits[0].toLowerCase()] = subbits[0]; // query[] indexes are now lowercase!
		};
	};
	return returnVals;
};

var query = parseQuery();

if($('.view-videos-latest-sidebar').length > 0){
	var imgcall = $('.views-field-field-video-thumbnail-value img');
	var origwidth = imgcall.width();
	var origheight = imgcall.height();
	
	var newwidth = Math.round(((70 / origheight) * origwidth));
	imgcall.height(70);
	imgcall.width(newwidth);
	imgcall.show();
}

if($('.videosearchresults').length > 0){
	var imgcall = $('.videoresult img');
	var origwidth = imgcall.width();
	var origheight = imgcall.height();
	
	var newwidth = Math.round(((125 / origheight) * origwidth));
	imgcall.height(125);
	imgcall.width(newwidth);
	imgcall.show();
}
