(function() {
try {
if(!ognc.exists) { throw "ogncObjUndefined"}

//UBK Commonly used functions/helpers
ubk = 
{
	isLoggedIn: null,
	exists: true,
	commentCount:0,
	curAggType:null,
	curAggAction:null,
	KCConnectUser:ognc.getCookie('KCConnectUser'),
	mlc:document.location.pathname,
	isActive:false,
	
	// Report data
	report_data: {
		content_id: 0,
		comment_id: 0,
		comment_location: null,
		comment_type: 'comment' // alternately it could be 'caption'
	},
	
    init: function() {
        // Allow console.log debugging cross all browsers
        try { console.log('...ubk is now running...'); } catch(e) { console = { log: function() {} } }
    },
	
	//Change view based on site auth
	kcLogIn : function(){
		if(this.KCConnectUser == ''){
			this.KCConnectUser = ognc.getCookie('KCConnectUser');
		}
		ubk.isLoggedIn = "KC";
		this.upDateLoginInfo();
		this.kcConnectView();
	},
	
	//Check to see is user is logged in tru site auth
	checkKCLogin : function(){
		if(this.KCConnectUser != ''){
			this.kcLogIn();
		}
	},
	
	//Controls login state
	upDateLoginInfo : function(){
		if(ubk.isLoggedIn == "FB"){
			$('#user').css('display','block');
			$('#login').css('display','none');
			$('.nli').hide();
			$('.fbli').show();
			$('.login_box').css('display','none');
			$('.fb_log_out').show();
		}else{
			$('#kc_login').css('margin-top','-7px');
			$('#kc_login').css('display','block');
			$('#user').css('display','none');
			$('.login_box').css('display','none');
			$('.nli').hide();
			$('.fbli').show();
			$('.log_out').show();
		}
	},
	
	//Apply user names to forms based on site auth
	kcConnectView : function(){
		
		var name = ognc.utils.getParameterFromQueryString('name', this.KCConnectUser);
		var email = ognc.utils.getParameterFromQueryString('email', this.KCConnectUser);
		
		/*Comment Form Name Field*/
		if($('#comments_name')){
			$('#comments_name').attr('value', name);
		}
		
		/*Ask Form Name Field*/
		if($('#ask_name')){
			$('#ask_name').attr('value', name);
		}
		
		if($('#ask_email')){
			$('#ask_email').attr('value', email);
		}
		
		/*Spoof It Form Name Field*/
		if($('#spoof_it_name')){
			$('#spoof_it_name').attr('value', name);
		}
		
		/*Create Ownit Forms*/
		if($('#name')){
			$('#name').attr('value', name);
		}
		
		/*Turn on share box for mission*/
		if($('#connect_share')){
			$('#connect_share ').css('display','block');
		}
	},
	
	//Header navigation highlight methods 
	headerNavSelected: function(argItem){
		$("#"+argItem).addClass("nav_selected");
	},

	headerNavUnSelected: function(argItem){
		$("#"+argItem).removeClass("nav_selected");
	},
	
	// Get samples common path -- deprecated, just link to /samples
	getSamples:function()
	{
		window.location = '/samples/overview';	
	},
	
	//Show video overlay
	showVideoFragment:function(contentID, videoID, videoTitle, divID, fragmentPath, endFrame)
	{
		ubk.content_id = contentID;
		ubk.video_id = videoID;
		ubk.video_title = videoTitle;
		ubk.end_frame = endFrame;
		ubk.showFragment(divID, fragmentPath);
	},
	
	//Show UGC overlay
	showUGCFragment:function(data, title, id, fragmentPath) {
		ubk.ugc_data = data;
		ubk.ugc_title = title;
		ubk.showFragment(id, fragmentPath);
	},
	
	//Show gen overlay
	showFragment:function(id, fragmentPath)
	{
		// clear out any previous content
		$("#overlay_content_inner").empty();
		
		// create the div		
		$('<div id="' + id + '"></div>').appendTo("#overlay_content_inner");
		
		// load the fragment
		$("#" + id).load(fragmentPath, '', 
		
			// when complete fade in
			function(){					
		   		ubk.createOverlay();
		 	});
		
		//Track Page Overlay View
		//ognc.tracking.pageTrack(fragmentPath);
	},
	
	//Overlay template
	createOverlay:function()
	{
		var windowHeight = $(document).height();
		$('#overlay').css('height', windowHeight);		
		$('#overlay').fadeIn("med");
		
		$("#page_container select").hide() /* IE6 Fix: for the select z-index bug */
		
		ubk.moveOverlay();
		window.setTimeout(ubk.moveOverlay, 100);
		window.setTimeout(ubk.moveOverlay, 500);
		window.onresize = ubk.moveOverlay;
		window.onscroll = ubk.moveOverlay;
	},
	
	//Adjust overlay based on browser window
	moveOverlay:function()
	{
		var yPos;
		var contentHeight = $("#overlay_content_container").outerHeight();
		
		// check for mission footer
		if($("#mission_footer").css('display') == 'none'){
			yPos = $(window).height() / 2 - contentHeight/2 + $(window).scrollTop();
		}else{
			yPos = ($(window).height() - $("#mission_footer").outerHeight() ) / 2 - contentHeight/2 + $(window).scrollTop();
		}
		
		// if the item is larger then available do not center
		if($("#mission_footer").css('display') == 'none'){
			if(contentHeight > $(window).height()){
				yPos  = $("#overlay_content_container").css('top');
			}
		}else{
			if(contentHeight  > $(window).height() - $("#mission_footer").outerHeight()){
				yPos  = 20;
				console.log(yPos);
			}
		}
		if(yPos <= 0) {yPos = 0;}
		//$("#overlay_content_container").css("top", yPos);
		$("#overlay_content_container").stop();
		$("#overlay_content_container").animate( { top:yPos}, 200 );
	},
	
	//Remove overlay from view
	closeOverlay:function()
	{
		$('#overlay').fadeOut("med", function() { 
			
			if($('#video_embed_flash').length) {
				window.document['video_embed_flash'].destroy();
			}
			
			$("#overlay_content_inner").empty(); 
		});
		$("#page_container select").show() /* IE6 Fix: for the select z-index bug */
		window.onresize = '';
		window.onscroll = '';
	},
	
	//Share button template
	shareItem:function(argItem,argContentType,title){
		title = (title)? title : "Share"; 
		ubk.updateMissionFooter('share',argContentType);
		ognc.tracking.conversionTrack('content',title,'UBK_Share','1','1',argItem);
	},
	
	//This will increment a like value by 1 when requested
	likeItem:function(argId,argContentType){
		if(argId){
			$.post("/apps/likes/set?id="+argId,'',
			  function(data){
				$('#like_'+argId).html('Like ('+data+')');
				//$('#like_'+argId).removeAttr("href");
			});
		 }
		
		ubk.updateMissionFooter('like',argContentType);
	},

	//This will get a total like count for one content item and return it to the requesting id
	getLikeCount:function(argId){
		if(argId){
			$.post("/apps/likes/get?id="+argId,'',
			  function(data){
				$('#like_'+argId).html('Like ('+data+')');
			});
		}
	},
	
	//This will get a total like count for one content item and return the total
	getLikeTotal:function(argId,argEle){
		if(argId){
			$.post("/apps/likes/get?id="+argId,'',
			  function(data){
				$(argEle).html(data);
			});
		}
	},
	
	//Confess Count
	confessCount:function(argPollId){
		ubk.updateMissionFooter('poll','poll',argPollId);
	},
	
	//This will increment a like value by 1 when requested
	stampItem:function(argId,argRedirect){
		if(argId){
			$.post("/apps/likes/set?id="+argId,'',
			  function(data){
				$('#stamp_'+argId).html('Stamp it ('+data+')');
				//$('#stamp_'+argId).removeAttr("href");
				ubk.updateMissionFooter('stamp','ad');
				//Redirect or Update Footer.
				if(argRedirect){
					window.location.replace('/get_real/view/detail?id='+argId+'&ugc_type=stamp_it&media_type=stamp_it');
				}
			});
		 }
	},
	
	//This will get a total stamp count for one content item and return it to the requesting id
	getStampCount:function(argId){
		if(argId){
			$.post("/apps/likes/get?id="+argId,'',
			  function(data){
				$('#stamp_'+argId).html('Stamp it ('+data+')');
			});
		}
	},
	
	//Captcha updater
	refreshCaptcha: function(argForm) {
		$(".captcha_img", argForm).attr("src", "/getcaptcha?cache_buster=" + (Math.random() * 1000000000));
	},
	
	//Form valadation 
	checkFields: function(data, argForm) {
		var do_submit = true;
		var errors = {}
		$("FormElements", data).children().each(function () {
			if($.trim($("ProfanityStatus", this).text()) == "Failed") {
				do_submit = false;
				
				if(this.tagName == "captcha_response") {
					errors[this.tagName] = "Text did not match. Try again."
					
				} else if($("[name=" + this.tagName + "]", argForm).length) {
					errors[this.tagName] = "Oops! Please resubmit without profanity.";
				}
			}
		});
		
		ubk.refreshCaptcha(argForm);
		
		$(argForm).validate().showErrors(errors);
		
		return do_submit;
	},
	
	//Profanity Checker
	checkProfanity: function(argForm, callback) {
        var f = $(argForm);
        var serializedForm = f.serialize();

        $.ajax({
			type: "POST",
			url: "/checkprofanity",
			data: serializedForm,
			success: callback,
			error: function(xrl, status, error) {
				console.log(xrl, status, error);
			}
        });
		
	},
	
	//Get Real View Link Generator
	goToViewPage:function(argId){
		window.location.replace('/get_real/view/detail?id='+argId);
	},
	
	//Get Real Story View Generator
	goToStoryViewPage:function(argId){
		window.location.replace('/get_real/view/detail_story?id='+argId);
	},
	
	/*Application Form Submit Method*/
	submitComment:function(argForm){
			
			ubk.checkProfanity(argForm, function (data) {
			
			if(ubk.checkFields(data, argForm) && !ubk.isActive) {
				
				ubk.isActive = true;
					
				//Turn off Form until request is sent
				if(argForm.comment_type.value == 'caption'){

					$('#spoof_it_form_container').fadeOut('fast', function() {
						$('#thank_you').fadeIn('slow');
					});
			
						//Close Form
						$("#spoof_it_hidden_form_fields").slideUp("slow");
						$("#spoof_it_hidden_login_forms").slideUp("slow");
				
				}else{
			
					$('#comments_form_container').fadeOut('fast', function() {
					    $('#thank_you').fadeIn('slow');
					 });
			
						//Close Form
						$("#comments_hidden_form_fields").slideUp("slow");
						$("#comments_hidden_login_forms").slideUp("slow");
				}
	 	
	
				$.ajax({
					type: "POST",
					url: "/apps/comments/add",
					data: $(argForm).serialize(),
					success: function(data) {
			
						$name = $('[name=comment_by]',argForm).val(); // save the name for later
						$content_id = $('[name=id]',argForm).val(); // save the content id for later
						$new_comment = $("#ajax_comment_template").clone();
						$new_comment.removeAttr("id");
				
						$(".user_name",$new_comment).text($('[name=comment_by]',argForm).val());
						//$(".comment_post_data",$new_comment).text("recently");
						$(".user_comment",$new_comment).text($('[name=comment_text]',argForm).val());
				
						//$("#comments_form_container").slideUp("slow", "easeInSine");
						$new_comment.prependTo("#comments_list");
						$new_comment.slideDown("slow", "easeOutSine");
						$("<li class=\"divider_medium comment_divider\"></li>").prependTo("#comments_list");
				
						argForm.reset();
			
						$('[name=comment_by]',argForm).val($name);
				
						//Update Comment Count
						ubk.commentCount = ubk.commentCount + 1;
						$('#comments_total').html('('+ubk.commentCount+')');
				
						if(argForm.comment_type.value == 'caption'){
							ubk.updateMissionFooter('spoof','ad');
							ognc.tracking.conversionTrack('content','spoof','UBK_CreateSpoof','2','1', $content_id);
							ubk.goToViewPage(data);
						}else{
					
							//Reset Form and Turn on once request is sent
							setTimeout("$('#thank_you').fadeOut('fast', function() {$('#comments_form_container').fadeIn('slow');})",2000);
					
							if(ubk.mlc == "/the_mission/sign"){
								ubk.updateMissionFooter('sign','declaration');
							}else{
								ubk.updateMissionFooter('comment','page');
								ognc.tracking.conversionTrack('content','comment','UBK_Comment','1','1', $content_id);
							}
						}
					
					 ubk.isActive = false;
				
					},
					error: function(xrl, status, error) {
						console.log(xrl, status, error);
				
						//Turn on error message if something goes wrong.
						if(argForm.comment_type.value == 'caption'){
							$('#spoof_it_form_container').fadeOut('fast', function() {
								   	$('#error').fadeIn('slow');
							});
						}else{
							$('#comments_form_container').fadeOut('fast', function() {
							    	$('#error').fadeIn('slow');
							 });
						}
					
					  ubk.isActive = false;
				
					}
				});
			}
		});
	},
	
	/*Focus Method for Ask Questions*/
	focusForm:function(argForm){
		
		    //Open form fields if focus on form
			$("#"+argForm+"_hidden_form_fields").slideDown("slow");
			$("#"+argForm+"_hidden_login_forms").slideDown("slow");
			
			//Check for blur of form and close
			$("body").click(function (event) {
				var found = false;
				jQuery.each($(event.target).parents(), function() {
					if(this.id == argForm + "_container"){
						found = true;
					}
				});
				if(!found){
					$("#"+argForm+"_hidden_form_fields").slideUp("slow");
					$("#"+argForm+"_hidden_login_forms").slideUp("slow");
					$("body").unbind('click');
				}
			});
	},
	
	//Item Report template
	reportItem:function(content_id, comment_id, comment_type){
		this.report_data.content_id = content_id;
		this.report_data.comment_id = comment_id;
		this.report_data.comment_type = comment_type;
		this.report_data.comment_location =  document.location;
		
		ubk.showFragment("report_item_overlay", "/apps/reportedugcs/getreasonslist");
		
		if(!this.report_data.comment_id){
			ognc.tracking.conversionTrack('content','Report','UBK_Report','1','',this.report_data.content_id);
		}else{
			ognc.tracking.conversionTrack('content','Report','UBK_Report','1','',this.report_data.content_id + "|" + ubk.report_data.comment_id);
		}
	},
	
	//Random Background template
	randomBackground:function()
	{
		
		// if we are in product section and not product homepage and oherwsie
		if( (document.location.toString().indexOf("/products/") > 0 && document.location.toString().indexOf("/products") != -1 ) || document.location.toString().indexOf("/products") < 0)
		{
			var axel = Math.random();
		    var ord = Math.round(axel * 4);
			$('#page_container').css({'background' : 'url("/img/shapes_' + String(ord) + '.png") no-repeat center top'});
			$('#page_container').addClass('fix_png');
		}
	
		
	},
	
	//Hot Topic link template
	gotoTopic: function(topicID) {
		//  get the doc location and check if we are in the QA section
		if(document.location.toString().indexOf('qa') != -1){
			document.location = '/real_answers/qa?topic=' + topicID;
		}else{
			document.location = '/real_answers/education?topic=' + topicID;
		}
		
	},
	
	//Set Base Share Buttons
	intShareButtons: function(){
		if($('.share')){
			addthis.button('.share');
		}
	},
	
	//Video view counter
	videoPlayed: function(contentID)
	{
		ubk.updateMissionFooter('view','video',contentID);
	},
	
	// mission footer
	updateMissionFooter: function(argAct,argType,argID){
	
			var argMLC = "";
			
			if (argID) {
				argMLC = this.mlc+'|'+argID;
			}else{
				argMLC = this.mlc;
			}
			
			$.post("/apps/aggregate/set?act="+argAct+"&type="+argType+"&mlc="+argMLC,'',
			  function(data){
				console.log(data);
					if($('#mission_footer')){
						$('#footer_updater').animate({ 
						        bottom: '40px'
						      }, 700, "easeOutBounce", ubk.incrementNumber);
						$('#footer_updater').css('display', 'block');
						$('#missions_total').removeClass('section_font_color');
						$('#missions_total').addClass('yellow_font');
						$('#footer_border').removeClass('section_background_color');
						$('#footer_border').addClass('yellow_background');
						$('#footer_updater').removeClass('section_background_color');
						$('#footer_updater').addClass('yellow_background');
					}
			});
	},
	
	// mission footer
	incrementNumber: function(){
		// get number
		var number = parseInt($('#missions_total').text().split(',').join(''));
		
		$('#missions_total').text(ubk.comma(number+1));
		
		var t=setTimeout(ubk.footerClose, 2000);
		
	},
	
	//footer close animation
	footerClose: function(){
		// animate up
		$('#footer_updater').animate({ 
		        bottom: '14px'
		 }, 400, "easeInSine", function(){
			$('#missions_total').removeClass('yellow_font');
			$('#missions_total').addClass('section_font_color');
			$('#footer_border').removeClass('yellow_background');
			$('#footer_border').addClass('section_background_color');
			$('#footer_updater').removeClass('yellow_background');
			$('#footer_updater').addClass('section_background_color');
			$('#footer_updater').css('display', 'none');
		});
	},
	
	//Add comma to footer number
	comma: function(number) {
		number = '' + number;
		if (number.length > 3) {
		var mod = number.length % 3;
		var output = (mod > 0 ? (number.substring(0,mod)) : '');
		for (i=0 ; i < Math.floor(number.length / 3); i++) {
		if ((mod == 0) && (i == 0))
		output += number.substring(mod+ 3 * i, mod + 3 * i + 3);
		else
		output+= ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
		}
		return (output);
		}
		else return number;
	},
	
	toggleMissionFooter: function() {
		if(document.location.href.indexOf("the_mission") == -1) { 
			$('#mission_stats #mission_link').css('display','inline');
		}
	}
	
}

ubk = window.ubk;

$(document).ready(function () {
    ubk.init();
	ubk.randomBackground();
	ubk.intShareButtons();
	ubk.checkKCLogin();
	ubk.toggleMissionFooter();
});

} catch(e) { console.log("error: " + e);}
})();

//Sharing Templates
var addthis_share =
{ 
	email_template: "UBK",
	email_vars: { description: $("meta[name='description']").attr("content") }
}

//Base Sharing Configuration
var addthis_config =
{
	ui_hover_direction:1,
	services_compact:"facebook,email,twitter,favorites,more",
	ui_cobrand:"Break The Cycle*",
	ui_header_background:"#000000",
	ui_offset_left:"-179",
	ui_offset_top:"-29",
	ui_header_color:"#ffffff",
	ui_click:true,
	data_track_linkback:true,
	data_ga_tracker: ognc.tracking.pageTracker,
	ui_use_addressbook:true
}