var BIMJS = (typeof BIMJS == "object") ? BIMJS : {}; //BIM JS namespace

BIMJS.commentFlag = function() {
	this.init = function() {
		$('.comment div.commentFlag').click(function(e) {
			var confirmFlag = confirm('This comment is inappropriate and should be reviewed.');
			if(confirmFlag) {
				var hrefStr = document.URL;
				$.get(
					'http://'+document.domain+'/internal', {
						flag : 'comment',
						commentID : $(e.target).prev().text(),
						contentID : hrefStr.substring(hrefStr.lastIndexOf("/")+1,hrefStr.lastIndexOf("."))
					}
				);
				$(e.target).replaceWith('<p class="commentflagged">This comment will be reviewed for appropriateness.</p>');
			}
			return false;
		});
	}
}

BIMJS.ynFlag = function() { //called from document ready function in silverdollar_flag_js
	this.init = function() {
		BIMJS.ynFlag.prototype.clickTarget.addClass('jqModal').click(function(e) {
			/*--- Commonly Used DOM Markers ---*/
			var columnsinnerEl = $('#columns-inner');
			var contentEl = $('#content');
			var sidebarEl = $('#sidebar');
			var textareaEl = $('form[name=ynFlag] textarea');
			/*--- Next 2 CSS Declarations Fix FF Bug That Pres Select Menu From Responding ---*/
			columnsinnerEl.css('overflow','visible'); //override silverdollar.css declaration
			contentEl.css('overflow','visible'); //override younews.css declaration
			sidebarEl.css('overflow','visible'); //override younews.css declaration
			/*--- Stop Default Action & e Propagation ---*/
			e.preventDefault();
			e.stopPropagation();
			e.cancelBubble = true; //MSIE
			BIMJS.ynFlag.prototype.lightboxEl.removeClass('hide').addClass('jqmWindow').css('width','380px').jqm({modal:true,overlay:0}).jqmShow(); //init element for modal window
			$('form[name=ynFlag] input[type=reset]').click(function(e) { // e handler to close lightbox... this is required as I need to clear out the prev defined inline styles when lightbox is closed
				columnsinnerEl.css('overflow','hidden');
				contentEl.css('overflow','hidden');
				sidebarEl.css('overflow','hidden');
				BIMJS.ynFlag.prototype.lightboxEl.jqmHide();
			});
			BIMJS.ynFlag.prototype.lightboxEl.jqmAddClose($('form[name=ynFlag] input[type=reset]')); //init element to close modal window
			$('form[name=ynFlag] select').change(function(e) {
				if($('form[name=ynFlag] select option:selected').val() == 'Other') {
					textareaEl.attr('class','show');
					textareaEl.attr('display','block');
				}
				else {
					textareaEl.attr('class','hide');
				}
			});
			$('form[name=ynFlag] input[type=submit]').click(function(e) {
				/*--- Stop Default Action & e Propagation ---*/
				e.preventDefault();
				e.stopPropagation();
				e.cancelBubble = true; //MSIE
				if($('form[name=ynFlag] select option:selected').val() == 'Select One') {
					if($(e.target).siblings().is('#invalidSelection') == false) {
						$(e.target).parent().append('<p id="invalidSelection">Please choose an option from the menu or click "Cancel".</p>');
					}
					else {
						$('#invalidSelection').text('Please choose an option from the menu or click "Cancel".');
					}
				}
				else if($('form[name=ynFlag] select option:selected').val() == 'Other' && textareaEl.val() == '') {
					if($(e.target).siblings().is('#invalidSelection') == false) { //pre writing out multiple invalidSelection paragraphs
						$(e.target).parent().append('<p id="invalidSelection">Please specify why you\'re flagging this content, choose another option from the menu or click "Cancel".</p>');
					}
					else {
						$('#invalidSelection').text('Please specify why you\'re flagging this content, choose another option from the menu or click "Cancel".');
					}
				}
				else {
					/*--- Return Styling Back To That Set In silverdollar.css and younews.css ---*/
					columnsinnerEl.css('overflow','hidden');
					contentEl.css('overflow','hidden');
					sidebarEl.css('overflow','hidden');
					BIMJS.ynFlag.prototype.lightboxEl.jqmHide(); //hide modal window
					BIMJS.ynFlag.prototype.clickTarget.replaceWith('This '+BIMJS.ynFlag.prototype.flagtypeStr+' has been flagged for moderation.');
					if($('form[name=ynFlag] select option:selected').val() == 'Other') {
						var formVal = 'element.body='+$('form[name=ynFlag] textarea').val();
					}
					else {
						var formVal = $(e.target).parent().serialize();
					}
					$.get( //post to yn submission queue
					'http://'+document.domain+'/m',
					BIMJS.ynFlag.prototype.getParamsStr+'&'+formVal//getParamsStr contains server-side data generated in silverdollar_flag_js
					);							
				}
			});
		});
	}
}

BIMJS.sendEmail = function() { //called from responseListener function in luckystar_emailForm; currently only useful for "luckystar" rev programs
	this.init = function() {
		var formEl = $('form[class=email]');
		$('#contactus h3').remove();
		formEl.replaceWith('<p>Thanks for contacting us. One of our representatives will get back to you shortly.</p>');
		$.get(
			document.baseURI,
			'sendmail=y&'+(formEl.serialize())
		);
	}
}

BIMJS.xhrGen = function() {
	this.init = function(e) {
		if(e != undefined) {
			e.preventDefault();
			e.stopPropagation();
			e.cancelBubble = true; //MSIE
		}
		$.ajax(BIMJS.xhrGen.prototype.optionsObj);
	}
}

BIMJS.parseStr = function(srcStr,str) {
	BIMJS.returnStr = $.trim(srcStr.substring(srcStr.indexOf(str)+1,srcStr.length)); //less than ideal; still investigating alternatives as I want to keep this property as cordoned-off as possible
	return BIMJS.returnStr;
}

BIMJS.newWindow = function(urlStr,winNameStr,featuresStr) {
	newWindow = window.open(urlStr,winNameStr,featuresStr);
	newWindow.focus();
}

function xhrStatus(configObj) { // displays loading graphic and msg
	if(configObj.hideArray) {
		var hideArray = configObj.hideArray;
		for(var i = 0;i<hideArray.length;i++) {
			$(hideArray[i]).hide();
		}
	}
	if(configObj.showArray) {
		var showArray = configObj.showArray;
		for(var i = 0;i<showArray.length;i++) {
			$(showArray[i]).show();
		}
	}
	var target = configObj.target;
	var content = configObj.content;
	var action = configObj.action;
	switch(action) {
		case('insertBefore'):
			$(content).insertBefore($(target));
			break;
		case('insertAfter'):
			$(content).insertAfter($(target));
			break;
		case('html'):
			$(target).html($(content));
			break;
		case('text'):
			$(target).text($(content));
			break;
	}
}

BIMJS.mediaViewer = function() {
	this.init = function(configObj) {
		BIMJS.mvHelper.call(this,configObj);
		this.autoscroll = function() {
			BIMJS.mvAutoscroll.call(this,configObj);
		}
		this.controlledscroll = function (action) {
			BIMJS.mvControlledScroll.call(this,configObj,action);
		}
		this.metadata = function() {
			BIMJS.mvMetadata.call(this,configObj);
		}
		this.modal = function() {
			BIMJS.jqModal.call(this,configObj);
		}
		this.navigation = function() {
			BIMJS.mvNavigation.call(this,configObj);
		}
		this.scroll = function() {
			BIMJS.mvScroll.call(this,configObj);
		}
	}
}

BIMJS.jqModal = function(configObj) { // requires jqModal.js and and jqModal.css
	var modalConfig = configObj.modalConfig;
	$.each(modalConfig.targetEl,function() {
		$(this).addClass('jqModal').click(function() { // bind evnt handler to open modal window
			$('.selected').removeClass('selected');
			configObj.currentIndex = $(modalConfig.targetEl).index(this);
			$($(configObj.linksObj).get(configObj.currentIndex)).addClass('selected');
			BIMJS.mvFullsize.call(this,configObj);
			if(configObj.metaConfig) {
				BIMJS.mvMetadata.call(this,configObj);
			}
			$(modalConfig.modalEl).removeClass('hide').addClass('jqmWindow').css(modalConfig.cssConfig).jqDrag().jqm(modalConfig.jqmConfig).jqmShow(); // init modal window
			$(modalConfig.modalEl).jqmAddClose($(modalConfig.closeEl)); // bind evnt handler to close modal window
			return false;
		});
	});
}

BIMJS.mvAutoscroll = function(configObj) {
	$.each(configObj.linksObj,function() {
		$(this).bind('autoScroll',function() {
			configObj.currentIndex = (configObj.currentIndex < configObj.endIndex) ? configObj.currentIndex + 1 : 0;
			BIMJS.mvFullsize.call(this,configObj);
			if(configObj.metaConfig) {
				BIMJS.mvMetadata.call(this,configObj);
			}
		});
	});
	setInterval(function() {
		var currentHeadline = $(configObj.linksObj)[configObj.currentIndex];
		$(currentHeadline).triggerHandler('autoScroll');
	},configObj.autoConfig.duration * 1000);
}

BIMJS.mvControlledScroll = function(configObj,action) {
	//to beable to start and stop the scroll from user interaction use this method instead of mvAutoscroll,
	//but you will need to define an mvIntervalTimer variable in the config object.
	if(configObj.mvIntervalTimer === "undefined"){
		$.each(configObj.linksObj,function() {
			$(this).bind('autoScroll',function() {
				configObj.currentIndex = (configObj.currentIndex < configObj.endIndex) ? configObj.currentIndex + 1 : 0;
				BIMJS.mvFullsize.call(this,configObj);
				if(configObj.metaConfig) {
					BIMJS.mvMetadata.call(this,configObj);
				}
			});
		});
	}
	if (action === "play") {
		configObj.mvIntervalTimer = setInterval(function() {
			var currentHeadline = $(configObj.linksObj)[configObj.currentIndex];
			$(currentHeadline).triggerHandler('autoScroll');
		},configObj.autoConfig.duration * 1000);
	} else {
		clearInterval(configObj.mvIntervalTimer);
	}
}

BIMJS.mvFullsize = function(configObj) {
	var nextIndex = (configObj.currentIndex < configObj.endIndex) ? configObj.currentIndex + 1 : 0;
	if(!$.browser.msie || $.browser.msie && _globalMediaArray[configObj.currentIndex].storyImgUrl.indexOf('.png') == -1 && _globalMediaArray[nextIndex].storyImgUrl.indexOf('.png') == -1) {
		$(configObj.fullimgEl).fadeOut('fast',function() {
			BIMJS.mvHelper.call(this,configObj);
			$(this).css('background-image','url('+_globalMediaArray[configObj.currentIndex].storyImgUrl+')').fadeIn('slow');
		});
	} else { //msie doesn't play nice w/ fadeIn/fadeOut when transparent PNGs are set as background-image
		BIMJS.mvHelper.call(this,configObj);
		$(configObj.fullimgEl).css('background-image','url('+_globalMediaArray[configObj.currentIndex].storyImgUrl+')');
	}
}

BIMJS.mvHelper = function(configObj) {
	$('.selected').removeClass();
	$($(configObj.linksObj).get(configObj.currentIndex)).addClass('selected');
}

BIMJS.mvMetadata = function(configObj) {
	var metaConfig = configObj.metaConfig;
	if(typeof(metaConfig.captionEl) !== 'undefined' && metaConfig.captionEl !== null){
		$(metaConfig.captionEl).text(_globalMediaArray[configObj.currentIndex].caption);
	}
	if(typeof(metaConfig.creditEl) !== 'undefined' && metaConfig.creditEl !== null){
		(_globalMediaArray[configObj.currentIndex].credit == '') ? $(metaConfig.creditEl).text('') : $(metaConfig.creditEl).text('Credit: '+_globalMediaArray[configObj.currentIndex].credit);
	}
	if(typeof(metaConfig.summaryEl) !== 'undefined' && metaConfig.summaryEl !== null){
		(_globalMediaArray[configObj.currentIndex].summary == '') ? $(metaConfig.summaryEl).html('') : $(metaConfig.summaryEl).html(_globalMediaArray[configObj.currentIndex].summary);
	}
	if(typeof(metaConfig.vidIndicatorEL) !== 'undefined' && metaConfig.vidIndicatorEL !== null){
		(_globalMediaArray[configObj.currentIndex].mediaXML == '') ? $(metaConfig.vidIndicatorEL).hide() : $(metaConfig.vidIndicatorEL).show();
	}
	if(typeof(metaConfig.titleEl) !== 'undefined' && metaConfig.titleEl !== null){
		(_globalMediaArray[configObj.currentIndex].title == '') ? $(metaConfig.titleEl).html('') : $(metaConfig.titleEl).html(_globalMediaArray[configObj.currentIndex].title);
	}
}

BIMJS.mvNavigation = function(configObj) {
	$.each(configObj,function(name,value) {
		if(typeof(value) === 'object') {
			$(this).bind('click',{name : name},function(e) {
				switch(e.data.name) {
					case('linksObj'):
						configObj.currentIndex = $(configObj.linksObj).index(this);
						break;
					case('nextEl'):
						configObj.currentIndex = (configObj.currentIndex < configObj.endIndex) ? configObj.currentIndex + 1 : 0;
						break;
					case('prevEl'):
						configObj.currentIndex = (configObj.currentIndex > 0) ? configObj.currentIndex - 1 : configObj.endIndex;
						break;
				}
				BIMJS.mvFullsize.call(this,configObj);
				if(configObj.callbackFn) {
					configObj.callbackFn(e,e.data.name);
				}
				if(configObj.metaConfig) {
					BIMJS.mvMetadata.call(this,configObj);
				}
				return false;
			});
		}
	});
}

BIMJS.mvScroll = function(configObj) { //requires jQuery.ScrollTo.js and jQuery.SerialScroll.js
	scrollConfig = configObj.scrollConfig;
	// configObj.scrollConfig uses a different property naming scheme for ease of implementation
	// redefine properties of scrollConfig to comply w/ properties expected by jQuery.ScrollTo.js and jQuery.SerialScroll.js
	scrollConfig = {
		/*--- Required Params ---*/
		target :  scrollConfig.parentEl, // element containing the elements to scroll
		items : scrollConfig.scrollEl, // elements to scroll
		prev : scrollConfig.prevEl, // navigation element that scrolls back one
		next : scrollConfig.nextEl, // navigation element that scrolls ahead one
		axis : scrollConfig.axis, // determines which axis to scroll on ('x' or 'y');
		step : scrollConfig.displayInt, // number of elements to display per scroll
		/*--- Optional Params ---*/
		navigation : scrollConfig.navEl, // optional navigation element
		duration : scrollConfig.durationInt, // optional integer that gets passed to easing equation to provide animation effect
		onAfter : scrollConfig.afterFn, //optional function that runs after scrolling
		onBefore : scrollConfig.beforeFn //optional function that runs prior to scrolling
	}
	$(scrollConfig.containerEl).serialScroll(scrollConfig);
}

BIMJS.reCaptcha = function() {
	this.init = function(optionsObj) {
		var targetEl = optionsObj.targetEl;
		var errorEl = optionsObj.errorEl
		var successFn = optionsObj.successFn;
		var errorFn = optionsObj.errorFn;
		$(targetEl).click(function(e) {
			if(Recaptcha.get_challenge() != '' && Recaptcha.get_response() != '') {
				BIMJS.xhrGen.prototype.optionsObj = {
					url: 'http://'+document.domain+'/internal',
					type: 'GET',
					data: 'get=recaptcha&challenge='+Recaptcha.get_challenge()+'&response='+Recaptcha.get_response(),
					dataType: 'json',
					cache: false,
					success: function(json,statusTxt) {
						if(json.validated == 'true') {
							successFn();
						} else {
							errorFn();
						}
					}
				}
			} else {
				errorFn();
			}
			var captchaXhr = new BIMJS.xhrGen();
			captchaXhr.init();
			return false;
		});
	}
}

BIMJS.commentJson = function(data,configObj) {
	var commentsConfig = configObj.commentsConfig;
	$.each(data.comments,function() {
		var author = (this.name == '' || this.name == 'anonymous') ? 'Anonymous' : this.name;
		$(commentsConfig.containerEl).append('<div class="comment-item"><p class="author">'+author+'</p><p class="comment">'+this.comment+'</p><p class="referrer">from <a href="'+this.storyUrl+'">'+this.contentTitle+'</a></p></div>');
	});
	$('.comment:odd').addClass('odd');
	if(configObj.scrollConfig) {
		BIMJS.mvScroll(configObj.scrollConfig);
	}
}

BIMJS.addInclude = function(includeHref,callbackFn) {
	var includeArray = new Array();
	$('link').add('script').each(function(i,value) {
		includeArray.push($(value).attr('href'));
		includeArray.push($(value).attr('src'));
	});
	if($.inArray(includeHref,includeArray) == -1) {
		includeHref = 'http://'+document.domain+'/includes/'+includeHref;
		if(includeHref.indexOf('.js') > -1) {
			var scriptEl = document.createElement('script');
			scriptEl.onload = callbackFn;
			scriptEl.onreadystatechange = function() { //IE
				if(this.readyState === 'loaded' || this.readyState === 'complete') {
					callbackFn();
				}
			};
			scriptEl.setAttribute('src',includeHref);
			scriptEl.setAttribute('type','text/javascript');
			document.getElementsByTagName('head')[0].insertBefore(scriptEl,document.getElementsByTagName('script')[0]); //ensures new include is first script element on page(so code is avail to all other calling methods)
		} else {
			$('<link rel="stylesheet" type="text/css" href="'+includeHref+'">').insertAfter('link:last');
		}
	}
}

BIMJS.sfHover = function() {
	this.init = function(hoverEls) {
		this.mouseover = function() {
			$(this).addClass('sfhover');
		};
		this.mouseout = function() {
			$(this).removeClass('sfhover');
		};
		$(hoverEls).hover(this.mouseover,this.mouseout);
	}
}


$(document).ready(function() {
    $("#share-tool a.modalOpen, #shareModalWindow .shareClose a.modalClose").click( function() {
      $("#shareModalWindow").toggleClass("hide");   
      return false;
    });
});
