var preoutput;
var width=screen.availWidth;
var height=screen.availHeight;
var resolution=width + "x" + height;

function escapeHash(string) {
  return string.replace(/#/g,'%23');
}

function GetStatsData(altURI, dynamicRefresh) {

  var dynamicRefresh = dynamicRefresh || false; 
  
    /* pduey: checking server name. production sites (www.brides.com, video.brides.com, origin.www.brides.com, etc.)
     *        need to log to stats.brides.com. at the time of this writing, we don't have a similar stats-only 
     *        web server/sensor setup in staging, so we'll just leave the hardcoded server name out until we do.
     */

    output = ""; // default
    var re = /.*www\.brides\.com|video\.brides\.com|clinique\.brides\.com|table\.brides\.com|tools\.brides\.com|upload\.brides\.com/;
    var curHost = document.location.host;
    // console.debug("server name is " + curHost);
    if (curHost.match(re)) {
      output = "http://stats.brides.com"; // if in prod
      // console.debug("matched production server name regular expression, prepending http://stats.brides.com to stats call");
    }
    output += '/js/stats/zag.js?Log=1';
    URLoutput = '';

    /* these items need to be appended to the URL value */
    if (typeof microsite != 'undefined'){
      URLoutput += '&microsite=' + microsite;
    }
	
	/* Tab section on forums landing page */
	if (typeof cookieTabs != 'undefined') {
		/*Handles redirect for /forums/recent.jspa && /forums/popular.jspa */
		var pqs = new ParsedQueryString();
		defaultQS = pqs.param('defaultTab');
		
		if (defaultQS && !dynamicRefresh) { //if defaultTab querystring exists
			tabSection = defaultQS.replace('#goallforums', '');
		} else {
			//use cookie value
			tabSection = cookieTabs.getCookie();
		}
		
		URLoutput += cookieTabs.getCookie() ? '&tabSection=' + tabSection : '&tabSection=allforums';	
		if (dynamicRefresh) {
			/*deletes second instance the tabSection param when tracking is initiated outside of the initial onload sequence.*/
		    URLoutput = URLoutput.replace(/(&tabSection=)\w+/g, ''); 
		}
		
	}
	
    if (typeof vendorListingId != 'undefined'){
      URLoutput += '&vendorListingId=' + vendorListingId;
    }
    if(typeof clipAction != 'undefined'){
      if ('content' == clipAction && typeof clippedContentId !='undefined'){
        URLoutput += '&clippedContentId=' + clippedContentId;
      } 
      else if ('image' == clipAction && typeof clippedImageId !='undefined'){
        URLoutput += '&clippedImageId=' + clippedImageId;
      }
      else if ('email' == clipAction && typeof emailAction != 'undefined'){
          URLoutput += '&emailAction=' + emailAction;
        if(typeof username !='undefined'){
          URLoutput += '&statEmailUsername=' + username;
        }
        if(typeof statEmailFrom !='undefined'){
          URLoutput += '&statEmailFrom=' + statEmailFrom; 
        }
        if(typeof statEmailTo !='undefined'){
          URLoutput += '&statEmailTo=' + statEmailTo;
        }
      }
    }
    if(document.getElementsByName('vs.statusCode').length != 0){
        URLoutput += '&statusCode=' + document.getElementsByName('vs.statusCode')[0].content;
    }
    if(dynamicRefresh) {
        URLoutput += '&dynamicRefresh=' + dynamicRefresh;
    }
    if(document.location.href.indexOf("?") == -1 && URLoutput != '') {
      URLoutput = '?' + URLoutput.substring(1);
    }
    /* these items need to be appended to the URL value */


    // pduey: if sending email to vendor from the vendor listing results page,
    // the vendor listing ID is not part of the URI. Lead reporting depends on that.
    // Rather than redo the vendor reporting data transformation, which is a big
    // stupid ugly mess, I'll just continue in the hacking tradition and fake it here.
    var outputURI = typeof altURI == "undefined" ? document.location.href : document.location.protocol + '//' + document.location.host + altURI;
    if (typeof vendorListingId != 'undefined'){
      var re = /\/local.*results\/\d+.*/;
      var curUrl = document.location.href;
    	if ( ! curUrl.match(re)) {
      	outputURI = outputURI.replace(/results/g, 'results/' + vendorListingId);
      	// console.debug("added vendor listing id to outputURI: " + outputURI);
  		}
		}


    // dwells:  video page tracking stuff
		if(typeof videoPathForStats != 'undefined' && videoPathForStats != '') {
			outputURI += "/" + videoPathForStats.replace(/\./g, "/");
			if(videoNameForStats != '') {
				outputURI +='/'+videoNameForStats;
			}
			outputURI += "/"
		} 


    /* keep these grouped as URL, REFERRER, screenres */	
    output += '&URL=' + escapeHash(outputURI) + URLoutput;
    output += '&REFERRER=' + (document.referrer);
    output += '&screenres='+resolution;
    /* keep these grouped as URL, REFERRER, screenres */
    if (typeof userData != "undefined" && userData != null) {
	output += '&email='+userData.email;
    }
    if (typeof impression == "string") {
      output += '&IMPRESSION=' + impression;
    }
    output += '&cachedefeat=' + (new Date()).getTime();
    
    var head = document.getElementsByTagName('head').item(0);
    var scriptTag = document.getElementById('loadScript');
    if(scriptTag) head.removeChild(scriptTag);
    script = document.createElement('script');
    script.src = output;
    script.type = 'text/javascript';
    script.id = 'loadScript';
    head.appendChild(script);
    return true;
}
GetStatsData();

/**
* @function jQuery
* @returns Object
* A mock-object to prevent errors in http://stats.brides.com/js/stats/zig.js
* this mock will need a false function or property for each use within this file. 
* try not to use it...
**/

if(typeof jQuery != "undefined" && jQuery.length != 0) {
  jQuery(document).ready(function () {
    jQuery('a[href^="http"]').add(jQuery('a[href*="redirect"]')).not(jQuery('div.DartAdUnit a')).not(jQuery('#navBar a')).not(jQuery('.redirectLoggerExclusion a')).not(jQuery('#localTextLinks a')).not(jQuery('#vendorInfoList ul.linkList a')).not(jQuery('#vendorfinder a')).not(jQuery('.localAdUnit a')).not(jQuery('a.history')).not(jQuery('a#print')).attr({target: '_new'}).add(jQuery('a[href$="pdf"]')).add(jQuery('#navBar #item13 a')).click(function(){return GetStatsData('/?external_link='+this.href+'?br_loc='+document.location)});
  });
}

