var timeOffset;
var launchPartsMate;
var partsMateKit;
var partsMateKitType;
var partsMateBrand;
var mediaURLRoot = (document.location.protocol=="https:"?"https://s3.amazonaws.com/":"http://")+"media.advantagehobby.com/";

function init() {
  if (launchPartsMate) {
    if (partsMateKit) {
      togglePF(partsMateKit);
    } else if (partsMateKitType && partsMateBrand) {
      togglePFForBrand(partsMateKitType,partsMateBrand);
    } else {
      togglePF();
    }
  }
  var localTime = (new Date()).getTime()/1000;
  timeOffset = localTime-serverTime;
  updateDOTDEnds();
  attachButtonHoverEvents();
  positionSavingsCenter();
}

function resized() {
  positionSavingsCenter();
}

function positionSavingsCenter() {
  var savingsCenter = $("savingsCenter");
  if (savingsCenter) {
    var savingsCenterFirstChild = $("savingsCenterFirstChild");
    if (savingsCenter.offsetLeft < 815) {
      savingsCenterFirstChild.style.marginLeft = (815 - savingsCenter.offsetLeft) + "px"; 
    } else {
      savingsCenterFirstChild.style.marginLeft = 0;
    }
  }
}

function updateDOTDEnds() {
  if ($("rightDOTD")) {
    // daily special updates each day a 1:05 am EST
    var localTime = (new Date()).getTime()/1000;
    var ends = dotdEnds - (localTime - timeOffset);
    var hours = parseInt(ends/60/60);
    ends = ends - (hours*60*60);
    var minutes = parseInt(ends/60);
    ends = ends - (minutes*60);
    var seconds = parseInt(ends);
    $("dotdEndsHours").innerHTML = hours;
    $("dotdEndsMinutes").innerHTML = minutes;
    $("dotdEndsSeconds").innerHTML = seconds;
    setTimeout("updateDOTDEnds()",1000);
  }
}

function attachButtonHoverEvents() {
  var inputs = document.getElementsByTagName("INPUT");
  for (var i=0;i<inputs.length;i++) {
    if (inputs[i].type == "image" && inputs[i].src.indexOf("buttons/") > -1) {
      addEvent(inputs[i],"mouseover",
        function(e) {  
          var e = e || event; 
	        var button = e.srcElement || e.target;
          button.src = button.src.replace(".gif","-over.gif"); 
        }
      );
      addEvent(inputs[i],"mouseout",
        function(e) { 
          var e = e || event; 
	        var button = e.srcElement || e.target;
          button.src = button.src.replace("-over.gif",".gif"); 
        }
      );
    }
  }
}

var pfIsOpen = false;

function togglePFForBrand(kitTypeId,manufacturerId) {
  var url = "/parts_finder/?KitTypeID="+kitTypeId+"&ManufacturerID="+manufacturerId;
  togglePFFinal(url);
}

function togglePF(kitId,kitPlanId,sku) {
  var url = "/parts_finder/?loaded=true";
  if (kitId) {
    url += "&KitID="+kitId;
    if (kitPlanId) {
      url += "&KitPlanID="+kitPlanId;  
      if (sku) {
        url += "&SKU="+sku;  
      }
    }
  }
  togglePFFinal(url);
}

function togglePFFinal(url) {
  var pf = $("partsFinder");
  if (pfIsOpen) {
    pfIsOpen = false;
    pf.style.display = "none";
    pfMask(0);
    $('pfIFrame').src='/parts_finder/';
  } else {
    this.closedX = findPosX(pf);
    pf.style.left = ((document.body.offsetWidth - 567) / 2)+"px";
    var vscroll = (document.all ? document.documentElement.scrollTop : window.pageYOffset);
    pf.style.top = vscroll+150+"px";
    pf.style.display = "block";
    pfIsOpen = true;
    pfMask(1);
    $('pfIFrame').src=url;
  }
}

function pfMask(toggle) {
  pMask(toggle);
}

function pMask(toggle) {
  var hide = new Array();
  for (var i=0;i<hide.length;i++) {
    if (e = $(hide[i])) {
      e.style.visibility = toggle ? "hidden" : "visible";
    }
  }
  var pageMask = $("pageMask");
  var ref = $("pageWrapper");
  pageMask.style.width = ref.offsetWidth+"px";
  pageMask.style.height = ref.offsetHeight+"px";
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    pageMask.style.backgroundImage= "url(/layout/blacktrans60back.png)";
    pageMask.style.backgroundRepeat="repeat";
  } else {
    pageMask.style.backgroundColor = "#000000";
    pageMask.style.MozOpacity = .60;
    pageMask.style.opacity = .60;
    pageMask.style.filter = "alpha(opacity=60)";
  }
  pageMask.style.display = toggle ? "block" : "none";
}


function toggleRegisterQuick(toggle) {
  pMask(toggle);
  var regPopUp = $("registerPopUp");
  if (toggle) {
    regPopUp.style.left = ((document.body.offsetWidth - 430) / 2)+"px";
    var vscroll = (document.all ? document.documentElement.scrollTop : window.pageYOffset);
    regPopUp.style.top = vscroll+200+"px";
    regPopUp.style.display="block";
    $("regIFrame").src="/register_quick.php";
  } else {
    regPopUp.style.display="none";
  }
}


/* main navigation */

var activeCategoryChoice;
var okToDeactivate = false;

function deactivateActiveCategoryChoice() {
  var divs = document.getElementsByTagName("div");
  for (var i=0; i<divs.length;i++) {
    if (divs[i].className.indexOf("submenu")>-1 && divs[i].className.indexOf("active") > -1) {
      divs[i].className = divs[i].className.replace(/(\s*active)|(active\s*)/,"");
    }
  }
  var choices = $("menus").getElementsByTagName("a");
  for (var i=0; i<choices.length;i++) {
    if (choices[i].className.indexOf("active") > -1) {
      choices[i].className = choices[i].className.replace(/(\s*active)|(active\s*)/,"");
    }
  }
  activeCategoryChoice = null;
}

function activateCategoryChoices(category,e,scroll) {
  var e = e || event; 
  e.cancelBubble=true;
	var link = e.srcElement || e.target;
  link.blur();
  scroll = typeof scroll != "undefined" && scroll;
  activateCategoryChoicesRaw(category);
  if (scroll) {
    window.scroll(0,0);
  }
}

function activateCategoryChoicesRaw(category) {
  if (category == activeCategoryChoice) {
    if (okToDeactivate) {
      deactivateActiveCategoryChoice();
    }
  } else {
    deactivateActiveCategoryChoice();
    var choices = $("menus").getElementsByTagName("a");
    for (var i=0; i<choices.length;i++) {
      if (choices[i].className.indexOf(category)>-1 && choices[i].className.indexOf('active')==-1) {
        choices[i].className = choices[i].className + " active"
      }
    }
    var divs = document.getElementsByTagName("div");
    for (var i=0; i<divs.length;i++) {
      if (divs[i].className.indexOf(category)>-1 && divs[i].className.indexOf("submenu")>-1 && divs[i].className.indexOf("active")==-1) {
        divs[i].className = divs[i].className + " active"
      }
    }
    activeCategoryChoice = category;
    okToDeactivate = false;
    setTimeout("okToDeactivate=true",500);
  }
}

function switchUniverse(universe) {
  $("menus").innerHTML = "";
  var client = new HTTPClient();
  client.makeRequest("Text","GET","/menus.php?universe="+universe,"",universeSwitched,universe);
}

function universeSwitched(response,universe) {
  var parts = response.split("~DIVIDER~");
  $("menus").innerHTML = parts[0];
  $("submenus").innerHTML = parts[1];
}

/* product page tabs */
function switchTab(tab) {
  // clear previous choice
  var choices = $("productTabs").getElementsByTagName("li");
  for (var i=0; i<choices.length;i++) {
    if (choices[i].className.indexOf("active") > -1) {
      choices[i].className = choices[i].className.replace(/(\s*active)|(active\s*)/,"");
    }
  }
  var contents = $("productTabContent").getElementsByTagName("div");
  for (var i=0;i<contents.length;i++) {
    if (contents[i].className.indexOf("tagContent") && contents[i].className.indexOf("active") > -1) {
      contents[i].className = contents[i].className.replace(/(\s*active)|(active\s*)/,"");
    }
  }
  // activate new choice
  var activeTab = $(tab+"Tab");
  activeTab.className = activeTab.className + " active";  
  var activeTabContent = $(tab+"TabContent");
  activeTabContent.className = activeTabContent.className + " active";
  setCookie("activeProductTab",productId+":"+tab);
}

function findPosX(obj) {
  var curleft = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  } else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function brandSelected(select) {
  var manufacturerid = select.options[select.selectedIndex].value;
  document.location="/manufacturers.php?manufacturerid="+manufacturerid;
}

function toggleMoreBrands() {
  var div = $("brandsFull");
  var show = div.style.display != "block";
  div.style.display = show ? "block" : "none";
  if (show) {
    addEvent(document.body,"click",toggleMoreBrands);
  } else {
    removeEvent(document.body,"click",toggleMoreBrands);
  }
}

function addEvent(elem,event,func) {
  if (elem.addEventListener) {
    elem.addEventListener(event, func, false);
  } else {
    elem.attachEvent("on"+event, func);
  }
}

function removeEvent(elem,event,func) {
  if (elem.removeEventListener) {
    elem.removeEventListener(event, func, false);
  } else {
    elem.detachEvent("on"+event, func);
  }
}

function pleaseLoginDealer() {
  alert("Dealers must log in to access product information and pricing");
}

function $(id) {
  return document.getElementById(id);
}

function setCookie(name, value, expires, path, domain, secure) {
  var today = new Date();
  today.setTime(today.getTime());
  if (expires) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expiresDate = new Date(today.getTime()+expires);
  document.cookie = name + "=" +escape(value) +
  (expires ? ";expires=" + expiresDate.toGMTString() : "") +
  (path ? ";path=" + path : "") +
  (domain ? ";domain=" + domain : "") +
  (secure ? ";secure" : "");
}

function getCookie(checkName) {
	var aAllCookies = document.cookie.split( ';' );
	var aTempCookie = '';
	var cookieName = '';
	var cookieValue = '';
	var bCookieFound = false;
	for (i=0;i<aAllCookies.length;i++ ) {
		aTempCookie = aAllCookies[i].split( '=' );
		cookieName = aTempCookie[0].replace(/^\s+|\s+$/g, '');
		if (cookieName == checkName) {
			bCookieFound = true;
			if (aTempCookie.length > 1) {
				cookieValue = unescape(aTempCookie[1].replace(/^\s+|\s+$/g, ''));
			}
			return cookieValue;
			break;
		}
		aTempCookie = null;
		cookieName = '';
	}
	if (!bCookieFound) {
		return null;
	}
}

function HTTPClient() { }

HTTPClient.prototype = {
  http: null,
  callback: function() { return null; },
  makeRequest: function() {
    var url;
    var data;
    var method = "POST"; // default method
    if (arguments.length > 3) {
      this.Type = arguments[0];
      method = arguments[1];
      url = arguments[2];
      data = arguments[3];
      this.postFunction = arguments[4];
      if (arguments.length > 5)
        this.carryObject = arguments[5];
    } else {
      // old
      url = arguments[0];
      data = arguments[1];
      this.postFunction = arguments[2];
    }
    if (window.XMLHttpRequest) {
      this.http = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      this.http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    var self = this;
    this.http.onreadystatechange = function() {
      if (self.http.readyState == 4) {
       if (self.http.status == 200) {
         if (self.postFunction) {
           if (self.Type == "Text") {
             eval('self.postFunction(self.http.responseText'+(self.carryObject?',self.carryObject':'')+')');
           } else if (self.Type == "XML") {
             eval('self.postFunction(self.http.responseXML.documentElement'+(self.carryObject?',self.carryObject':'')+')');
           } else {
             alert(self.Type);
           }
         }
        } else {
          alert("There was a problem retrieving the data:\\n" + self.http.statusText);
        }
      }
      self.callback(self);
    }
   this.http.open(method=="POSTRAW"?"POST":method, url, true);
    if (method == "POST")
      this.http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    this.http.send(data);
  }
}