var d = document;

String.prototype.trim = function () {
	return this.replace(/^\s+|\s+$/g, "");
}

var tstrings = {
  searchsite: $('#txtSearch').val()
};

$(document).ready(function() {
	$("#appleslider").show();
	init();
	customizeAdmin();
	imagemapinit();
	resourceLibraryLinks();

	//image map hover events
	$("a[@href^=http]").each(function() {
		if(this.href.indexOf(location.hostname) == -1) {
			$(this).click(function(){window.open(this.href);return false;});
		}
	});

	// Hides the extra junk when loading in an iFrame - might need to tailor specifically to traction
	var isInIFrame = (window.location != window.parent.location) ? true : false;
	if(isInIFrame == true){
		$("#appleslider").hide();
		$("#iconicnav").hide();
		$("#header").hide();
		$("#footer").hide();
		$("#navigation").hide();
		$("#navcontain").hide();
		$(".tabs").hide();
		$(".sbico").hide();
		$("#neighborhoodtop").hide();
		$("#BetaEasyInvokeButton").hide();
		$("#wrapper").css('width', '100%');
		cssObj = {'width' : '730px',
				  'float' : 'left'}
		$("#wrapper-inner").css(cssObj);
		$("#content").css('width', '730px');
		$("#col-right").css('width', '520px');
		$("html").css('margin', '0');
	}
});
//end doc ready


resourceLibraryLinks = function(){
	//Resc Lib icon replacement
	$('.views-field-field-static-path-value p a').html("<span class='rliconholder'></span>");
	$('.views-field-field-static-path-value p a[href^=mailto]').find('.rliconholder').addClass("email");
	$('.views-field-field-static-path-value p a[href$=".pdf"]').find('.rliconholder').addClass("pdf");
	$('.views-field-field-static-path-value p a[href$=".gif"], .views-field-field-static-path-value p a[href$=".jpg"], .views-field-field-static-path-value p a[href$=".jpeg"]').find('.rliconholder').addClass("image");
	$('.views-field-field-static-path-value p a[href$=".ppt"], .views-field-field-static-path-value p a[href$=".pptx"], .views-field-field-static-path-value p a[href$=".pot"]').find('.rliconholder').addClass("ppt");
	$('.views-field-field-static-path-value p a[href$=".avi"], .views-field-field-static-path-value p a[href$=".mov"], .views-field-field-static-path-value p a[href$=".wmv"]').find('.rliconholder').addClass("video");
	$('.views-field-field-static-path-value p a[href$=".dxf"], .views-field-field-static-path-value p a[href$=".dwg"]').find('.rliconholder').addClass("cad");
	$('.views-field-field-static-path-value p a[href$=".zip"]').find('.rliconholder').addClass("archive");
	$('.views-field-field-static-path-value p a[href$=".txt"]').find('.rliconholder').addClass("text");
	$('.views-field-field-static-path-value p a[href$=".dot"], .views-field-field-static-path-value p a[href$=".doc"], .views-field-field-static-path-value p a[href$=".docx"]').find('.rliconholder').addClass("word");
	$('.views-field-field-static-path-value p a[href$=".mdb"], .views-field-field-static-path-value p a[href$=".accdb"]').find('.rliconholder').addClass("access");
	$('.views-field-field-static-path-value p a[href$=".xls"], .views-field-field-static-path-value p a[href$=".xlsx"]').find('.rliconholder').addClass("excel");
	$('.views-field-field-static-path-value p a[href$=".vsd"], .views-field-field-static-path-value p a[href$=".vdx"]').find('.rliconholder').addClass("visio");
	$('.views-field-field-static-path-value p a[href$=".html"], .views-field-field-static-path-value p a[href$=".htm"]').find('.rliconholder').addClass("web");
	$('.views-field-field-static-path-value p a[href$=".exe"]').find('.rliconholder').addClass("exe");
}

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();
			};
		};
	};
		
	// 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);
				};
			});
	});
};


// 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 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();
};

function setActiveStyleSheet(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;
				};
			};
		};
	};
};

function setStyles() {
	var cookie = readCookie("armStyles");
	var title = cookie ? cookie : "small";
	createCookie("armStyles", title, 365);
	setActiveStyleSheet(title);
};

function createCookie(name,value,days) {
  if (days || 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=/";
};

function readCookie(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();


//JQUERY BELOW
//AUTHOR JSARTIN

// Sidebar in the employee youtube video section
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();
}

//Sort and build dropdowns in product download centers
if($('.dlcenter').length > 0){
	$('.dlcenter').hide();
	var dlcenteritem = 1;
	var doc_types = new Array();
	var doc_item = new Array();
	while($('.dlcenter .views-row-' + dlcenteritem).length > 0){
		if($.trim($('.dlcenter .views-row-' + dlcenteritem).html()).length > 0){
			doc_types[doc_types.length] = $('.dlcenter .views-row-' + dlcenteritem + ' .doctype').html();
			doc_item[doc_item.length] = $('.dlcenter .views-row-' + dlcenteritem + ' .docli').html();
		}
		dlcenteritem++;
	}
	var dropdownboxid = 0;
	var dropdownfullhtml = '';
	var currcount = '1';
	//start first box
	var dropdownheadhtml = '<div class="dldrophead drop-' + dropdownboxid + '"><span class="dldropheadtext">' + doc_types[0];
	var dropdownitemhtml = doc_item[0];
	var currtype = doc_types[0];
	for(i=1;i<doc_types.length;i++){
		if(doc_types[i] == currtype){
			dropdownitemhtml += doc_item[i];
			currcount++;
		}
		else{
			//build previous box
			dropdownfullhtml += dropdownheadhtml;
			dropdownfullhtml += ' (' + currcount + ' ' + ((currcount > 1) ? Drupal.t('items') : Drupal.t('item')) + ')';
			dropdownfullhtml += '</span></div><div class="dldropcontent drop-' + dropdownboxid + '-content"><ul>'
			dropdownfullhtml += dropdownitemhtml;
			dropdownfullhtml += '</ul></div><br style="clear:both"/>';
			//start new box
			currtype = doc_types[i];
			dropdownboxid++;
			dropdownheadhtml = '<div class="dldrophead drop-' + dropdownboxid + '"><span class="dldropheadtext">' + doc_types[i];
			dropdownitemhtml = doc_item[i];
			currcount = '1';
		}
	}
	//finish last box
	dropdownfullhtml += dropdownheadhtml;
	dropdownfullhtml += ' (' + currcount + ' ' + ((currcount > 1) ? Drupal.t('items') : Drupal.t('item')) + ')';
	dropdownfullhtml += '</span></div><div class="dldropcontent drop-' + dropdownboxid + '-content"><ul>'
	dropdownfullhtml += dropdownitemhtml;
	dropdownfullhtml += '</ul></div><br style="clear:both"/>';
	$('.dlcenter').html(dropdownfullhtml);
	$('.dlcenter').show();
}

$(".dldrophead").click(function(){
		$(this).toggleClass("active").next().slideToggle("slow");
		return false; //Prevent the browser jump to the link anchor
});

//toggle neighborhood
$("#neighborhoodmenutoggle").click(function(){
    if($.browser.msie)
      $('#neighborhoodmenucontent').toggle();
    else
      $('#neighborhoodmenucontent').slideToggle('slow');
    $(this).toggleClass('closebtn');     
		return false; //Prevent the browser jump to the link anchor
});

//mouseovers on image map init
function imagemapinit(){
  if($('area').length > 0){
    $('body').append('<div id="imagemaptip"></div>');
     var tip = $('#imagemaptip');
    $('area').hover(function(){  
      tip.html($(this).attr('alt'));
      tip.show(); //Show tooltip
    }, function() {
      tip.hide(); //Hide tooltip
    }).mousemove(function(e) {
      var mousex = e.pageX + 20; //Get X coodrinates
      var mousey = e.pageY + 20; //Get Y coordinates
      var tipWidth = tip.width(); //Find width of tooltip
      var tipHeight = tip.height(); //Find height of tooltip

      //Distance of element from the right edge of viewport
      var tipVisX = $(window).width() - (mousex + tipWidth);
      //Distance of element from the bottom of viewport
      var tipVisY = $(window).height() - (mousey + tipHeight);

      if ( tipVisX < 20 ) { //If tooltip exceeds the X coordinate of viewport
          mousex = e.pageX - tipWidth - 20;
      } if ( tipVisY < 20 ) { //If tooltip exceeds the Y coordinate of viewport
          mousey = e.pageY - tipHeight - 20;
      }
      //Absolute position the tooltip according to mouse position
      tip.css({  top: mousey, left: mousex });
    });
  }
}

// popup ISSD
function issdpop(userlang) {
  var popurl= '/interactivediagram/?module=diagram&action=view&id=1' + userkey + '&lang=' + userlang;
  var settings='height=' + (screen.height * .85) + ',width=' + (screen.width * .85) + ',scrollbars=no,toolbar=no,location=no,status=no,menubar=no, resizable=no, dependent=no, left=' + (.5 * (screen.width * .15)) + ', top=35';
  winpops = window.open(popurl,"",settings);
}
