var isIE6 = false;

var PGISite = null;

var omniture = new omnitureTracking();



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;

    }

    if (node.parentNode.nodeName == "product") {

      urlObj[nodeURL].product = 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("站点地图解析失败：" + e);

    }

  }

  this.init = function(map) {

    this.builder = new siteBuilder(map);

  }

  var xml = new xmlLoader("/cn/cn/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 = [];

    var prodlinks = [];

    for (var i=0; i < arr.length; i++) {

      var href = arr[i];

      var title = this.map[arr[i]].title;

      var txt = '<a href="'+href+'">'+title+'</a>';

      if (this.map[arr[i]].product) {

        prodlinks.push(txt);

      }

      else {

        if (!this.map[arr[i]].solution) { // removing solution tier from breadcrumbs

          links.push(txt);

        }

      }

    }

    if (this.map[loc].subtitle) {

      var subtitle = this.map[loc].subtitle;

      var txt = '<a href="'+href+'">'+subtitle+'</a>';

      prodlinks.push(txt);

    }

    var bc_txt = links.join(" &gt; ");

    if (prodlinks.length > 0) {

      bc_txt += " &gt; " + prodlinks.join(": ");

    }

    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.asp") > -1) {

      var ref = document.referrer;

      if (ref == "http://www.pgs-marketing.com/forms/processForm.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();

}

/* omniture tracking class */

function omnitureTracking() {

  this.build = function() {

    this.set(s);

    s.t();

  }

  this.set = function(s) {

    var loc = getLocation();

    if (loc == "/" || loc == "/default.asp") {

      s.channel = "Home";

      s.pageName = "Premiere Homepage"

      return;

    }

    var section_match = getSection();

    var sections = {

    	"cos" : {title: "COS", solution:"/cn/cn/cos/"},

      "con" : {title: "Conferencing", solution:"/cn/cn/conferencing/"},

      "dtf" : {title: "Desktop Fax", solution:"/cn/cn/desktop-fax/"},

      "emk" : {title: "eMarketing", solution:"/cn/cn/emarketing/"},

      "not" : {title: "Notifications", solution:"/cn/cn/notifications/"},

      "doc" : {title: "Document Delivery", solution:"/cn/cn/document-delivery/"},

      "arm" : {title: "Accounts Receivables", solution:"/cn/cn/accounts-receivables/"}

    };

    var channel = (sections[section_match]) ? sections[section_match].title : null;

    if (channel) {

      s.channel = channel;

    }

    if (sections[section_match] && loc == sections[section_match].solution) {

			s.pageName = channel + " Homepage";

		}

    if (loc.indexOf("contact-us.asp") > -1) {

      var bus_type = (loc.indexOf("/cn/cn/enterprise-solutions/") > -1) ? "LB" : "SB";

      var form_type = ((loc.indexOf("contact-us.asp") > -1)) ? "Contact Us" : "Demos and Trials";

      var page = channel + " " + bus_type + " " + form_type;

      s.pageName = page + " Step 1";

      s.products = ";" + page;

      if (loc.indexOf("contact-us.asp") > -1) {

        s.evar5 = page;

        s.events = "event6";

      }

      if (loc.indexOf("demos-and-trials.asp") > -1) {

        s.evar6 = page;

        s.events = "event8";

      }

    }

    if (loc.indexOf("confirm.asp") > -1) {

      var ref = document.referrer;

      var bus_type = (ref.indexOf("/cn/cn/enterprise-solutions/") > -1) ? "LB" : "SB";

      var form_type = ((ref.indexOf("contact-us.asp") > -1)) ? "Contact Us" : "Demos and Trials";

      var page = channel + " " + bus_type + " " + form_type;

      s.pageName = page + " Step 2";

      s.products = ";" + page;

      if (form_type == "Contact Us") {

        s.events = "event7";

      }

      if (form_type == "Demos and Trials") {

        s.events = "event9";

      }

    }

  }

  this.build();

}

/* form class */

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 Premiere Global Services?",

		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;

		}

    // check for blank required fields

    var noblank = true;

    var noblank_msg = "以下字段为空白：\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 += "请输入有效电子邮件地址。\n";

      myForm.email.focus();

      validated = false;

      if (myForm.email2) {

        if (myForm.email.value != myForm.email2.value) {

          validated_msg += "输入的电子邮件地址不匹配。\n";

          myForm.email2.focus();

          validated = false;

        }

      }

    }

    if (myForm.phone && !this.validPhone(myForm.phone.value)) {

      validated_msg += "请输入有效电话号码（XXXXXXXXXX 或 XXX-XXX-XXXX 格式）。\n<";

      myForm.phone.focus();

      validated = false;

    }

    if (myForm.zip && !this.validZip(myForm.zip.value)) {

      validated_msg += "请输入有效邮政编码（XXXXX 格式）。";

      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+))+@\w+\.\w+/i;

    var result = input.match(validaddress);

    if (result == null) {

      return false;

    }

    else {

      return true;

    }

  }

  this.validPhone = function(input) {

    var validphone1 = /^\d{3}-\d{3}-\d{4}$/i;

    var validphone2 = /^\d{10}$/i;

    var result1 = input.match(validphone1);

    var result2 = input.match(validphone2);

    if (result1 == null && result2 == null) {

      return false;

    }

    else {

      return true;

    }

  }

  this.validZip = function(input) {

    var validphone = /^\d{5}$/i;

    var result = input.match(validphone);

    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" : "/cn/cn/conferencing/confirm.asp",

      "not" : "/cn/cn/notifications/confirm.asp",

      "emk" : "/cn/cn/emarketing/confirm.asp",

      "dtf" : "/cn/cn/desktop-fax/confirm.asp",

      "doc" : "/cn/cn/document-delivery/confirm.asp"

    };

    if (value == "Sales") {

      this.form.action = "http://www.pgs-marketing.com/forms/processForm.php";

      this.form.returnURL.value = "http://" + location.host + actions[section_match];

    } else {

      this.form.action = actions[section_match];

    }

  }

  this.setupRegistration = function() {

    var section_match = getSection();

    var actions = {

      "con" : "/cn/cn/conferencing/confirm.asp",

      "not" : "/cn/cn/notifications/confirm.asp",

      "emk" : "/cn/cn/emarketing/confirm.asp",

      "dtf" : "/cn/cn/desktop-fax/confirm.asp",

      "doc" : "/cn/cn/document-delivery/confirm.asp"

    };

		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);

}

/* login popup functions */

function loginPopupInit(sectionID) {

  var section = (sectionID) ? sectionID : loginPopupSection();

  var xml = new xmlLoader("/cn/cn/xml/login/"+section+".htm", loginPopupXML, {"sectionID" : section});

  xml.load();

}

function loginPopupXML(xmlObj, args) {

  var content_div = document.getElementById("h_login_popup_content");

  var html_content = null;

	try {

		var xmlObject = xmlObj;

		var root = xmlObject.getElementsByTagName('h_l_popup')[0];

		for (var i=0; i < root.childNodes.length; i++) {

			var child1 = root.childNodes.item(i);

			if(child1.nodeName.toLowerCase() == 'content') {

				for (var j=0; j < child1.childNodes.length; j++) {

					var child2 = child1.childNodes.item(j);

					if(child2.nodeName.toLowerCase().indexOf('cdata') > -1) {

						html_content = child2.nodeValue;

					}

				}

			}

		}

	} catch( e ) {}

	content_div.innerHTML = html_content;

	loginPopupCookie(args.sectionID);

	document.getElementById("h_login_popup").className = "visible";

	loginPopupTrack();

}

function loginPopupTrack() {

	var section_match = getSection();

  var sections = {

  	"cos" : "cos",

    "con" : "conferencing",

    "dtf" : "desktop-fax",

    "emk" : "emarketing",

    "not" : "notifications",

    "doc" : "document-delivery",

    "arm" : "accounts-receivables"

  };

  var section = sections[section_match];

  section = (!section) ? "home" : section;

	pageTracker._trackPageview("/cn/cn/"+section+"/login attempt");

}

function loginPopupSection() {

  var loc = getLocation();

  var section_match = getSection();

  var sections = {

    "con" : "con_mym",

    "dtf" : "dtf_f2m",

    "emk" : "emk_acc",

    "/cn/cn/notification-reminders-alerts/enterprise-solutions" : "not_myp",

    "not" : "not_irg",

    "doc" : "doc_myp",

    "arm" : "arm_vre"

  };

  var section = sections[section_match];

  section = (!section) ? "con_mym" : section;

  return section;

}

function loginPopupClose() {

  document.getElementById("h_login_popup").className = "hidden";

}

function loginPopupCookie(section) {

  var cookies = new cookieManager();

  var user = cookies.getCookie("pg_popup_user_"+section);

  if (user != null) {

    if (document.getElementById("h_l_p_input_user")) {

      document.getElementById("h_l_p_input_user").value = user;

    }

  }

  var inputs = document.getElementById("h_login_popup_content").getElementsByTagName("input");

  for (var i=0; i < inputs.length; i++) {

    if (inputs[i].name == "gobutton") {

      inputs[i].onclick = function() {

        var input_user = document.getElementById("h_l_p_input_user").value;

        cookies.setCookie("pg_popup_user_"+section, input_user, null, "/");

      }

    }

  }

}

/* functions */

function getSection() {

  var loc = getLocation();

  var section_match = false;

  var sections = {

  	"/cn/cn/cos/" : "cos",

    "/cn/cn/conferencing/" : "con",

    "/cn/cn/desktop-fax/" : "dtf",

    "/cn/cn/emarketing/" : "emk",

    "/cn/cn/notifications/" : "not",

    "/cn/cn/document-delivery/" : "doc",

    "/cn/cn/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("/cn/cn/css/pgi_section_default.css");

		}

		else {

    	addStyleSheet("/cn/cn/css/pgi_section_"+ section_match +".css");

    }

  }

  if (!section_match && loc != "/" && loc != "/default.asp") {

		addStyleSheet("/cn/cn/css/pgi_section_default.css");

	}

  if (loc == "/" || loc == "/default.asp") {

    addStyleSheet("/cn/cn/css/pgi_home.css");

    addStyleSheet("/cn/cn/css/pgi_section_con.css");

    section_match = "home";

  }

  // add contact form CSS if contact us page

  if (loc.indexOf("contact-us.asp") > -1 || loc.indexOf("registration.asp") > -1 || loc.indexOf("sign-up.asp") > -1 || loc.indexOf("try-it-now.asp") > -1 || loc.indexOf("/cn/cn/netspoke/demos-and-trials.asp") > -1) {

    addStyleSheet("/cn/cn/css/pgi_contact.css");

  }

  document.getElementsByTagName("html")[0].className = section_match;

}

function addFlash(file, div, id, params) {

	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" || div == "main_flash_narrow") {

		if (!hasflash || !hasversion) {

			var cookies = new cookieManager();

			var seen_error = cookies.getCookie("PGi-Seen-Flash-Error");

			if (seen_error != "Yes") {

			    alert("PremiereGlobal.com 錘g癳 Adobe Flash Player OS0  亯穬梍鬴}Y剉SO寶鲖N}廙Q9嶔f癳");

				cookies.setCookie("PGi-Seen-Flash-Error", "Yes", null, "/");

			}

		  var msg = document.createElement("div");

		  msg.id = "main_msg";

		  msg.innerHTML = '<img src="/cn/cn/img/home/arrow_orange.png" style="vertical-align:middle" /> PremiereGlobal.com 錘g癳 Adobe Flash Player OS0  亯穬梍鬴}Y剉SO寶鲖N}<a target="_blank" rel="nofollow" href="http://www.adobe.com/go/getflashplayer">MQ9嶔f癳</a>';

		  var parent = document.getElementById("main");

		  var ref = document.getElementById("main_flash");

      parent.insertBefore(msg, ref.nextSibling);

      addStyleSheet("/cn/cn/css/pgi_noflash.css");

    }

  }

  var bg = (params && params.bgcolor) ? params.bgcolor : "#ffffff";

  var wmode = (params && params.wmode) ? params.wmode : "opaque";

	var so = new SWFObject(file, id, "100%", "100%", "9.0.124.0", bg);

	so.addParam("wmode", wmode);

  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() {

  if (document.getElementById("main_flash") || document.getElementById("main_flash_narrow")) {

    var filo = new Font("filosofiaregular.swf", {tags:"span", classFilter:"sectionHeadline"});

    filo.replace();

    if (getLocation() == "/" || getLocation() == "/default.asp") {

      var filohome = new Font("filosofiaregular.swf", {tags:"span", classFilter:"titleText"});

      filohome.replace();

    }

  }

  else {

    var filo = new Font("filosofiaregular.swf", {tags:"h1"});

    filo.replace();

  }

}

function setupForm(form) {

  if (!form.func) {

    form.func = new formFunctions(form);

  }

}


