var addthis_pub="ogilvysap";
var addthis_offset_top = 40;
var addthis_offset_left = 60;
var tracker = null;

$(document).ready(function(){

    fadeThumbs ();        
    wireExternalLinks ();
    wireTelwebForTracking();
    
	// attach track behavior to footerlinks. 
	// if class name has "contactus"
	// give it a track key
	// necessary b/c jquery 'starts with' broken for className
	$('.footerCopy a').each( function() {
	    var str = $(this).attr("class");
	    if (str.match(/contactus_/)) {
	        $(this).attr("trackKey","contact us");
	    }
	});
	
	$("a[href^='http:']").not("a[className*='simpleLink']").not("[trackKey]").attr("trackKey","exit to SAP");

	if (typeof $.initTracker != 'undefined') {	
	    tracker = $.initTracker( 'omniture', {
				    XmlUrl: '/assets/xml/trackdata.xml', 
				    ExtraTrackData: {
					    "Homepage Load" : {
					    },
					    "download PDF" : {
						    'getFileName': function() { 
						                return window.location.href;
						    }
					    }
				    },
				    ExtraGlobalHolders: {
				        GETCULTURECODE: function() { return OMNI_culture;  },
				        getPageName: function() { 
				            var loc = window.location.href;
				         	var arr = loc.split('/');
				            var out = "";
				            $.each(arr,function(i,n) {
				                if (n.toString().indexOf(".aspx") != -1) {
				                    out = n.replace("#",""); // get rid of pound sign
				                }				
				            });  
				            return out;
				        },
				        getPageNumber: function() {
				            return $(this).attr("page");
				        },
				        getPDFTitle: function() {
				            var str = $(this).parent().parent().find("h3").text();
				            return trim(str);
				        },
				        'button text': function() { return $(this).text(); },
				        'button url': function() { return $(this).attr('href'); },
				        'textOrTitle': function() { 
							var value = $(this).text();
							
							if( value.length == 0 ) {
								value = $(this).attr('title');
							} 
							
							return value;
				        }
				    },
				    TestMode: false,
				    ShowMissingHolderWarnings: false,
				    ShowOnlyReportedData: false,
				    ShowDebugInfo: false,
				    SanityCheckEnabled: false,
				    SanityCheckMissingOnly: false
			    });
    } // end check
    // now set some tracking rules
    
	
});

function shareThis() {
	console.log("YEP ITS ME");
   var url = window.location.href.replace(/(.*)(?=[.]aspx)[.]aspx#\/*{([^}]*)}\/*/gi,"$1/$2") // escape(window.location.href).replace(/%3A/i,":")
   var title = document.title; 
   addthis_options = 'email, delicious, newsvine, google, bookmarks, yahoobkm, digg, myweb, live, ask, facebook, reddit, technorati, stumbleupon, twitter';
   addthis_share_subject = 'Link of Interest: ';
   addthis_open(document.getElementById("shareLink"), '',url, title);
   tracker.track("open addThis",{});
}

function shareThisOut() {
    // do nothing
}

function fadeThumbs() {
	$("img.thumb").fadeTo("fast", 0.8); 
	$("img.thumb").hover(function(){
		$(this).fadeTo("fast", 1.0); 
		},function(){
			$(this).fadeTo("fast", 0.8); 
	});

	$("div.wideThumb").fadeTo("fast", 0.8); 
	$("div.wideThumb").hover(function(){
		$(this).fadeTo("fast", 1.0); 
		},function(){
			$(this).fadeTo("fast", 0.8); 
    });
}

function wireExternalLinks() {
	$("a[href^='http://']:not(.popup,.videoLink,[href*='" + location.hostname + "'])").attr ("target", "_blank");
	$("a[href^='https://']:not(.popup,.videoLink,[href*='" + location.hostname + "'])").attr ("target", "_blank");
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function wireTelwebForTracking() {
    $("a.footerLink").each( function() {
        if (this.className.match("letuscallyou")!=null) {
            $(this).attr("trackkey","teleweb call")
        }
        if (this.className.match("chatwithus")!=null) {
            $(this).attr("trackkey","teleweb chat")
        }
        if (this.className.match("emailus")!=null) {
            $(this).attr("trackkey","teleweb email")
        }
    });
}

/* Google Website Optimizer Conversion Script */
function doGoal(accountId, experimentId) {
	try {
		var pageTracker=_gat._getTracker(accountId);
		pageTracker._trackPageview("/" + experimentId + "/goal");
	}catch(err){}
}
/* End of Google Website Optimizer Conversion Script */


var PageTiles = function() {
	var tileRequest = [], tileRequestsComplete = 0, paginateEvent = false, _this;

	return {
		setupTilesPaginationInColumns: function(pageMoniker) {
			_this = this; //reference to the parent object
			$(document).bind('tileRequestsComplete', _this.updateEvents);

			if ($('#leftColumnTilesContainer').length > 0) { tileRequest[tileRequest.length] = 'left'; }
			if ($('#middleColumnTilesContainer').length > 0) { tileRequest[tileRequest.length] = 'middle'; }
			if ($('#rightColumnTilesContainer').length > 0) { tileRequest[tileRequest.length] = 'right'; }
		    
			var len = tileRequest.length;
			for(var i=0; i<len; i++) {
				_this.getTiles(pageMoniker, tileRequest[i], 1);
			}
		},

		//make call to get page tiles and renders in page
		getTiles: function(pageMoniker, columnPos, pageNumber) {
			var index = parseInt(pageNumber);
			var data = {"pageMoniker": pageMoniker, "columnPos": columnPos};
			SAP.Aurora.Web.ServiceModel.Renderer.GetTileListHtml(pageMoniker, columnPos, index, _this.renderTiles, null, data);
		},

		//callback/return from GetTileListHtml(). See getTiles()
		renderTiles: function(result, data) {
			var $tileContainer = $('#' + data.columnPos + 'ColumnTilesContainer');
			$tileContainer.html(result);

			$tileContainer.find('.featurePager a').bind('click', function() {
				paginateEvent = true;
				tracker.track('pagination', { ele: this });
				_this.getTiles(data.pageMoniker, data.columnPos, $(this).attr('page'));
				return false;
			});
	    
			tileRequestsComplete++;

			if (tileRequest.length === tileRequestsComplete || paginateEvent === true) {
				$(document).trigger('tileRequestsComplete');
			}
			
			paginateEvent = false;
		},
		
		//if all tile requests are complete, do any additional updates
		updateEvents: function(e) {
			fadeThumbs();
			wireExternalLinks();
			wirePopups();
		}
	}; //returning
}();

/**
 * Called by the Flash when the user clicks 'Next' at the end of a video.
 * @param {String} index The index of the current video.
 * @param {String} ID The ID of the current video.
 */
function getVidIndexFromFlash(index, ID) {
	FlashVideoIO.videoIndexFromFlash(index, ID);
}
