// Public vars
var staticSiteURL = 'static.selinc.com';

/* Temporary wrapper function for our old Google Analytics pageTracker to the new _gaq.push version
once content block cleanup is complete, remove.*/
pageTracker = new Object();
pageTracker._trackPageview = function (data) {
	_gaq.push(['_trackPageview', data]);
}
/*End*/

// function for returning an item from the query string
request = new Object();
request.QueryString = function (key, _default) {
	if (_default == null) _default = "";
	key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regex = new RegExp("[\\?&]" + key + "=([^&#]*)"),
			qs = regex.exec(window.location.href);
	if (qs == null) {
		return _default;
	}
	else {
		return qs[1];
	}
}

function onTemplateLoaded(experienceID) {
  $('.bc_loader').hide();
}
function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; }
    }
}

function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

function handleEnter(evt, checkId, actionId) {
    var key,sender;
    if (window.event)
    { // IE
        key = evt.keyCode;
    }
    else if (evt.which)
    { // Netscape/Firefox/Opera
        key = evt.which;
    }
    
    if (evt.currentTarget)
    { // Firefox/?
        sender = evt.currentTarget;
    }
    else if (evt.srcElement)
    { // IE
        sender = evt.srcElement;
    }
    
    if ((key == 13) && (sender.id == checkId))
    {
        __doPostBack(actionId, '');
        evt.returnValue = false;
    }
}

// For logging downloads, looks for any link with a class of LogDownload and adds this onclick event.
// We can specify contentid and folder by having data- attributes in the href, 
// examples:data-contentid="123456"  data-folder="Test Folder"
// if data-contentid is not located it will try and find id= in the links href
// If no contentID is given -1 will be passed, in this case a folder is required (assuming no content in CMS)
// if folder is not specified the async handler will use the contentid to find its folder
function logDownload(elm) {
	var linkTo = elm.attr('href'),
		folder = elm.attr('data-folder'),
		contentID = -1,
		data = 'contentid=';
	// find the contentid
	if ($(this).attr('data-contentid')) {
		contentID = elm.attr('data-contentid');
	}
	else if (linkTo.indexOf('id=') > -1) {
		var newCID = parseInt(linkTo.substr(linkTo.indexOf('id=') + 3), 10);
		if (!isNaN(newCID)) {
			contentID = newCID;
		}
	}
	if (contentID == -1 && !folder && linkTo.indexOf(staticSiteURL)) {
		// find the folder and file name of the secure file
		// the folder info should always start at the 6th position (crosses fingers)
		var fArray = linkTo.split('/');
		folder = '';
		for (var i = 6; i < fArray.length; i++) {
			folder += '/' + fArray[i];
		}
	}
	// add the contentID
	data += contentID;
	// only pass a folder if one is given, if folder is empty 
	// we assume there is a contentID in which case the server code
	// will attempt to find it in Ektron, if not it will fail
	if (folder) {
		data += '&folder=' + folder;
	}
	$.ajax({
		url: "/utils/logdownload.ashx",
		type: "POST",
		data: data,
		complete: function (xhr, textStatus) {
			location.href = linkTo;
		}
	});
}

/* 
Following functions are for determining height and width of browser window and logging it with Analytics 
*/
function getWidthAndHeight() {
	return $(window).width() + "x" + $(window).height();
}

//resize (this resize bind method via http://stackoverflow.com/questions/2996431/javascript-detect-when-a-window-is-resized)
$(window).resize(function () {
	if (this.resizeTO) {
		clearTimeout(this.resizeTO);
	}

	this.resizeTO = setTimeout(function () {
		$(this).trigger('resizeEnd');
	}, 800);
});

//resize bind
$(window).bind('resizeEnd', function () {
	_gaq.push(['_trackEvent', 'Browser Dimensions', 'Resize', getWidthAndHeight()]);
	_gaq.push(['_trackEvent', 'Browser Width', 'Resize', $(window).width().toString()]);
	_gaq.push(['_trackEvent', 'Browser Height', 'Resize', $(window).height().toString()]);
});

// OnLoad function
$(function () {
	// log windows height and width on page load to Google analytics.
	_gaq.push(['_trackEvent', 'Browser Dimensions', 'Initial Size', getWidthAndHeight()]);
	_gaq.push(['_trackEvent', 'Browser Width', 'Initial Size', $(window).width().toString()]);
	_gaq.push(['_trackEvent', 'Browser Height', 'Initial Size', $(window).height().toString()]);

	// for any items that have a class of LogDownload
	$('.LogDownload').click(function (event) {
		// prevent the href link from firing (or it will abort the async call)
		event.preventDefault();
		logDownload($(this));
	});

	// search through a couple of our main containers A tags and see if they 
	// have an href with static.selinc.com in it, if so attach the logging click event
	$('#contentContainer a, #twoColumnContainer a').each(function () {
		if ($(this).attr('href') && $(this).attr('href').indexOf(staticSiteURL) >= 0) {
			$(this).click(function (event) {
				// prevent the href link from firing (or it will abort the async call)
				event.preventDefault();
				logDownload($(this));
			});
		}
	});
});
