var isIE6 = false;
var PGISite = null;
addSectionCSS();
addLoadEvent(buildSite);
addLoadEvent(replaceSIFR);

/* cookie manager class */
function cookieManager() {
	this.setCookie = function(name, value, days) {
		var d = new Date();
		d.setDate(d.getDate() + days);
		document.cookie = name + "=" + escape(value) + ((days == null) ? "" : ";expires=" + d.toGMTString());
	};
	this.getCookie = function(name) {
		var s = name + "=";
		var ca = document.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( s ) == 0 )
				return c.substring( s.length, c.length );
		}
		return null;
	};
	this.eraseCookie = function(name) {
		this.setCookie(name, "", -1 );
	};
}
/* XML loader class */
function xmlLoader(url, callback, args) {
  var xml_loader = this;
  this.url = url;
  this.callback = callback;
  this.args = args;
  this.xmlhttp = null;
  this.reqChange = function() {
		if (xml_loader.xmlhttp != null && xml_loader.xmlhttp.readyState == 4) {
			if (xml_loader.callback != null && typeof(xml_loader.callback) == 'function' ) {
				xml_loader.parser(xml_loader.xmlhttp.responseText);
			}
			xml_loader.xmlhttp = null;
		}
  }
  this.parser = function(text) {
    var parsed_xml = null;
  	try {
  		if(window.ActiveXObject && /Win/.test(navigator.userAgent)) {
  			var v = ['Msxml2.DOMDocument.3.0', 'Microsoft.XMLDOM'];
  			for(var i=0; i < v.length; i++) {
  				try {
  					var o = new ActiveXObject( v[i] );
  					o.async = false;
  					o.loadXML(text);
  					parsed_xml = o; //return o;
  				} catch(e) { alert(e); }
  			}
  		} else if(DOMParser) {
  			var o = new DOMParser();
  			parsed_xml = o.parseFromString(text, 'text/xml'); //return o.parseFromString(text, 'text/xml' );
  		}
  	} catch(e) { alert(e); } 
  	xml_loader.callback(parsed_xml, args);
  }
  this.load = function() {
    if (this.xmlhttp != null) {
      this.xmlhttp.onreadystatechange = this.reqChange;
      this.xmlhttp.open("GET", url, true);
      this.xmlhttp.send(null);
    }
  }
  try {
  	this.xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
  } catch(e) {
  	try {
  		this.xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
  	} catch(e2) {
  		try {
  			this.xmlhttp = new XMLHttpRequest();
  		} catch(e3) {
  			alert(e + ' // ' + e2 + ' // ' + e3);
  		}
  	}
  }
}
/* sitemap parser class */
function siteMap() {
  this.errors = [];
  this.builder = null;
  this.parse = function(node, urlObj, sitemap) {
    var nodePath = node.getAttribute("path");
    var nodeTitle = node.getAttribute("title");
    var nodeSubTitle = node.getAttribute("subtitle");
    var nodeURL, nodeBreadCrumbs;
    if (node.parentNode.getAttribute("url")) {
      nodeURL = node.parentNode.getAttribute("url") + nodePath;
      var arr = urlObj[node.parentNode.getAttribute("url")].breadcrumbs.slice();
      if (nodeURL != node.parentNode.getAttribute("url")) {
        arr.push(nodeURL);
      }
      nodeBreadCrumbs = arr;
    }
    else {
      nodeURL = nodePath;
      nodeBreadCrumbs = [nodePath];
    }
		node.setAttribute("url", nodeURL);
		if (!urlObj[nodeURL]) {
		  urlObj[nodeURL] = {};
    }
		if (nodeTitle) {
      urlObj[nodeURL].title = nodeTitle;
    }
    if (nodeSubTitle) {
      urlObj[nodeURL].subtitle = nodeSubTitle;
    }
    if (nodeBreadCrumbs) {
      urlObj[nodeURL].breadcrumbs = nodeBreadCrumbs;
    }
    if (node.getAttribute("focus")) {
      urlObj[nodeURL].focus = node.getAttribute("focus");
    }
    if (!node.getAttribute("focus") && node.parentNode.getAttribute("focus")) {
      urlObj[nodeURL].focus = node.parentNode.getAttribute("focus");
    }
    if (node.nodeName == "solution") {
      urlObj[nodeURL].solution = true;
    }
		for (var i=0; i < node.childNodes.length; i++) {
      var current = node.childNodes[i];
      if (current.nodeType == 1) {
        sitemap.parse(current, urlObj, sitemap);
      }
		}
  }
  this.build = function(xmlObj, args) {
  	try {
  	  var parser = args.parser;
      var urls = {};
  		var xml = xmlObj;
  		var root = xml.getElementsByTagName("root")[0];
  		args.sitemap.parse(root, urls, args.sitemap);
  		args.sitemap.init(urls);
  	} catch(e) {
      args.sitemap.errors.push("site map parsing failed: " + e);
    }
  }
  this.init = function(map) {
    this.builder = new siteBuilder(map);
  }
  var xml = new xmlLoader("/xml/sitemap.xml", this.build, {sitemap: this});
  xml.load();
}
/* sitemap builder class */
function siteBuilder(map) {
  this.map = map;
  this.breadcrumbs = function() {
    var loc = getLocation();
    if (!this.map[loc]) { return; }
    var div = document.getElementById("breadcrumbs");
    if (!div) { return; }
    var arr = this.map[loc].breadcrumbs; 
    var links = [];
    for (var i=0; i < arr.length; i++) {
      var href = arr[i];
      var title = this.map[arr[i]].title;
      var txt = '<a href="'+title+'</a>';
      if (arr[i] != "/conferencing/") {
				links.push(txt);
			}
    }
    if (this.map[loc].subtitle) {
      var subtitle = this.map[loc].subtitle;
      var txt = ''+href+'">'+subtitle+'</a>';
      links.push(txt);
    }
    var bc_txt = links.join(" &gt; ");
    div.innerHTML = bc_txt;
  }
  this.navigation = function() {
    var nav = document.getElementById("sidenav");
    if (!nav) { return; }
    var href = getLocation(location.href.toLowerCase().split("?")[0].split("#")[0]);
    href = href.split("#")[0];
    var anchors = nav.getElementsByTagName("a");
    for (var i=0; i < anchors.length; i++) {
      if (anchors[i].href.toLowerCase() == href) {
        anchors[i].parentNode.className = "selected";
        if (anchors[i].parentNode.parentNode.parentNode.nodeName.toLowerCase() == "li") {
          anchors[i].parentNode.parentNode.parentNode.className = "selected";
        }
      }
    }
  }
  this.focus = function() {
    var loc = getLocation();
    if (loc.indexOf("confirm.php") > -1) {
      var ref = document.referrer;
      if (ref == "/conferencing/confirm.php" || ref == "") {
        var questions_div = document.getElementById("channel_phone_callout");
        if (questions_div) { questions_div.className = "questions_default"; }
        return;
      }
      else {
        var loc = getLocation(ref.split(location.host)[1]);
      }
    }
    if (!this.map[loc] || !this.map[loc].focus) { return; }
    var focus = this.map[loc].focus;
    var focus_div = document.getElementById("focus");
    if (focus_div) { focus_div.className = "focus_"+focus; }
    var questions_div = document.getElementById("channel_phone_callout");
    if (questions_div) { questions_div.className = "questions_"+focus; }
  }
  this.breadcrumbs();
  this.navigation();
  this.focus();
 
}
function formFunctions(form) {
  this.form = form;
  this.labels = {
		firstName : "First Name", lastName : "Last Name", email : "Email", phone : "Phone", city : "City", state : "State", zip : "Zip/Postal Code", country : "Country",
		emailCategory : "Contact Category", supportType : "Type of Support", jobTitle : "Job Title", company : "Company/Organization", hearAbout : "How did you hear about us?",
		challenges : "Challenges", satisfaction : "Satisfaction", monthlyVolume : "Monthly email volume", sendMethod : "Current send method"
	}
  this.validate = function(myForm) {
  	var requiredFields = {};
  	for (var i=0; i < myForm.required.value.split(",").length; i++) {
  		var input = myForm.required.value.split(",")[i];
  		var label = this.labels[input];
  		requiredFields[label] = myForm[input];
		}
		if (requiredFields["Contact Category"] && requiredFields["Contact Category"].value == "Customer Service") {
			requiredFields["Type of Support"] = myForm.supportType;
		}
		if (requiredFields["Contact Category"] && requiredFields["Contact Category"].value == "Sales") {
			requiredFields["How did you hear about us?"] = myForm.salesSource;
		}
    // check for blank required fields
    var noblank = true;
    var noblank_msg = "You left the following required field(s) blank:\n";  
    for (var i in requiredFields) {
    	if (requiredFields[i].length && !requiredFields[i].type) {
    		var checked = false;
    		for (var j=0; j < requiredFields[i].length; j++) {
					if (requiredFields[i][j].checked) {
						var checked = true;
					}
				}
				if (!checked) {
					noblank_msg += i + "\n";
					noblank = false;
				}
    	}
    	else {
	      if (requiredFields[i].value == "" || requiredFields[i].value.match(/^[\n\f\r\t\v\s]+$/)) {
	        noblank_msg += i + "\n";
	        requiredFields[i].focus();
	        noblank = false;
	      }
	    }
    }
    if (!noblank) {
      alert(noblank_msg);
      return false;
    }
    // check for valid email address, phone, zip
    var validated = true;
    var validated_msg = "";  
    if (myForm.email && !this.validEmail(myForm.email.value)) {
      validated_msg += "Please enter a valid email address.\n";
      myForm.email.focus();
      validated = false;
      if (myForm.email2) {
        if (myForm.email.value != myForm.email2.value) {
          validated_msg += "The email addresses entered do not match.\n";
          myForm.email2.focus();
          validated = false;
        }
      }
    }
    if (myForm.phone && !this.validPhone(myForm.phone.value)) {
      validated_msg += "Please enter a valid phone number.\n";
      myForm.phone.focus();
      validated = false;
    }
    /*if (myForm.zip && !this.validZip(myForm.zip.value)) {
      validated_msg += "Please enter a valid zip code.";
      myForm.zip.focus();
      validated = false;
    }*/
    if (!validated) {
      alert(validated_msg);
      return false;
    }
    if (myForm.action.indexOf("#") > -1) {
      this.setAction(myForm.formID.value);
    }
    return true;
  }
  this.validEmail = function(input) {
    var validaddress = /^[\w\-\.]+@[\w\-\.]+$/i;
    var result = input.match(validaddress);
    if (result == null) {
      return false;
    }
    else {
      return true;
    }
  }
  this.validPhone = function(input) {
    var validphone = /^[\d\+\(\)\s\-]+$/i;
    var hasdigits = /\d/i;
		var result1 = input.match(validphone);
		var result2 = input.match(hasdigits);
		if (result1 == null || result2 == null) {
			return false;
		}
    else {
      return true;
    }
  }
  this.validZip = function(input) {
    var validzip = /^[a-zA-Z0-9\s]+$/i;
    var result = input.match(validzip);
    if (result == null) {
      return false;
    }
    else {
      return true;
    }
  }
  this.setAction = function(value) {
    var loc = getLocation();
    var section_match = getSection();
    this.form.cat.value = section_match;
    var actions = {
      "con"  : "/conferencing/confirm.php",
      "not"  : "/conferencing/confirm.php",
      "emk"  : "/conferencing/confirm.php",
      "dtf"  : "/conferencing/confirm.php",
      "doc"  : "/conferencing/confirm.php"
    };
    this.form.action = actions[section_match];
  }
  this.setupRegistration = function() {
    var section_match = getSection();
    var actions = {
      "con"  : "/conferencing/confirm.php",
      "not"  : "/conferencing/confirm.php",
      "emk"  : "/conferencing/confirm.php",
      "dtf"  : "/conferencing/confirm.php",
      "doc"  : "/conferencing/confirm.php"
    };
		this.form.returnURL.value = "http://" + location.host + actions[section_match];
	}
  this.toggle = function(value) {
    var divs = this.form.getElementsByTagName("div");
    for (var i=0; i < divs.length; i++) {
      if (divs[i].className.indexOf("hide") > -1) {
        divs[i].style.display = "none";
      }
    }
    var selected = value.toLowerCase().substr(0,4);
    var showDiv = document.getElementById("toggle_" + selected);
    if (showDiv) {
      showDiv.style.display = "block";
    }
  }
  if (this.form.name == "registrationForm") {
		this.setupRegistration();
	}
}
/* global functions */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
function addScript(url) {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.src = url;
  head.appendChild(script);
}
function addStyleSheet(url) {
  var head = document.getElementsByTagName("head")[0];
  var link = document.createElement("link");
  link.type ="text/css";
  link.rel = "stylesheet";
  link.href = url;
  head.appendChild(link);
}
function getSection() {
  var loc = getLocation();
  var section_match = false;
  var sections = {
    "/about-us/" : "con",
    "/conferencing/" : "con",
    "/desktop-fax/" : "dtf",
    "/emarketing/" : "emk",
    "/notifications/" : "not",
    "/document-delivery/" : "doc",
    "/accounts-receivables/" : "arm"
  };
  for (var i in sections) {
    if (loc.indexOf(i) > -1) {
      section_match = sections[i];
      break;
    }
  }
  return section_match;
}
function addSectionCSS() {
  var loc = getLocation();
  var section_match = getSection();
  var defaults = {"cos":""};
  if (section_match) {
  	if (defaults[section_match] == "") {
			addStyleSheet("/css/pgi_section_con.css");
			
		}
		else {
    	addStyleSheet("/css/pgi_section_"+ section_match +".css");
    }
  }
  if (!section_match && loc != "" && loc != "index.php") {
		addStyleSheet("/css/pgi_section_con.css");
	}
  if (loc == "" || loc == "index.php") {
    addStyleSheet("/css/pgi_home.css");
    addStyleSheet("/css/pgi_section_con.css");
  }
  // add contact form CSS if contact us page
  if (loc.indexOf("contact-us.php") > -1 || loc.indexOf("registration.php") > -1 || loc.indexOf("offices.php") > -1 || loc.indexOf("sign-up.php") > -1 || loc.indexOf("try-it-now.php") > -1 || loc.indexOf("/netspoke/demos-and-trials.php") > -1) {
    addStyleSheet("/css/pgi_contact.css");
  }
}
function addFlash(file, div, id, bgcolor) {
/*
  var cookies = new cookieManager();
  var user = cookies.getCookie("pg_popup_user_"+section);
  if (user != null) {
  cookies.setCookie("pg_popup_user_"+section, input_user, null, "/");
*/
	var hasflash = new Font().hasFlash;
	var flashversion = deconcept.SWFObjectUtil.getPlayerVersion();
	var hasversion = true;
  if (flashversion.major <= 9) {
    if (flashversion.major < 9) {
      hasversion = false;
    }
    else {
      if (flashversion.minor >= 0) {
        if (flashversion.rev < 124) {
          hasversion = false;
        }
      }
    }
  }
  if (div == "main_flash") {
		if (!hasflash || !hasversion) {
			var cookies = new cookieManager();
			var seen_error = cookies.getCookie("PGi-Seen-Flash-Error");
			if (seen_error != "Yes") {
				alert("PremiereGlobal.com is optimized for the latest Adobe Flash Player.  For a better experience, download a free update.");
				cookies.setCookie("PGi-Seen-Flash-Error", "Yes", null, "/");
			}
		  var msg = document.createElement("div");
		  msg.id = "main_msg";
		  msg.innerHTML = '<img src="<?php echo "$site_root" ?>img/home/arrow_orange.png" style="vertical-align:middle" /> PremiereGlobal.com is optimized for the latest Adobe Flash Player.  For a better experience, download a <a target="_blank" rel="nofollow" href="<?php echo "$site_root" ?>http://www.adobe.com/go/getflashplayer">free update</a>.';
		  var parent = document.getElementById("main");
		  var ref = document.getElementById("main_flash");
      parent.insertBefore(msg, ref.nextSibling);
    }
  }
  var bg = (!bgcolor) ? "#ffffff" : bgcolor;
	var so = new SWFObject(file, id, "100%", "100%", "9.0.124.0", bg);
	so.addParam("wmode", "opaque");
  so.write(div);
}
function getLocation(input) {
	var loc;
	if (input) {
    loc = input.toLowerCase().split("%2d").join("-").split("%2D").join("-");
	}
	else {
		loc = location.pathname.toLowerCase().split("%2d").join("-").split("%2D").join("-");
	}
	return loc;
}
function openWindow(anchor, w, h) {
  window.open(anchor.href, "_blank", "resizable=1,location=0,status=0,menubar=0,toolbar=0,"+"width="+w+",height="+h);
}
function buildSite() {
  PGISite = new siteMap();
}
function replaceSIFR() {
  var filo = new Font("filosofiaregular.swf", {tags:"h1"});
  filo.replace();
}
function setupForm(form) {
  if (!form.func) {
    form.func = new formFunctions(form);
  }
}
function showMe(id) { // This gets executed when the user clicks on the checkbox
var obj = document.getElementById(id);
if (obj.style.display=="none") { // if it is checked, make it visible, if not, hide it
obj.style.display = "block";
} else {
obj.style.display = "none";
}
}