/* Article votes */

function articleVoteChangeImages(articleId,score) {
	for (i=1;i<=5;i++) {
		var img = jQuery("#nw_articleVoteImage_"+articleId+"_"+i);
		if (i<=score) {
			img.attr("src",img.attr("src").replace("rate-off.gif","rate-on.gif"));
		} else {
			img.attr("src",img.attr("src").replace("rate-on.gif","rate-off.gif"));
		}
	}
}

function articleVoteHover(articleId,score) {
	articleVoteChangeImages(articleId,score);
}

function articleVoteOut(articleId) {
	var score = jQuery("#nw_articleAvgScore_"+articleId).attr("value");
	articleVoteChangeImages(articleId,score);			
}

function detectVotingFromEmail() {
	var anchor = location.hash;
	if (!!anchor && /#nw-vote-\d+\?\d/.test(anchor)) {
		var articleId = anchor.substring(9,anchor.indexOf("?"));
		var score = anchor.substring(anchor.indexOf("?")+1);
		var link = jQuery("#nw_articleVoteLink_"+articleId+"_"+score).click();
	}
}

function articleVoteAction(articleId,score) {
	var articleVoteUrl = jQuery("#nw_articleVoteUrl_"+articleId).attr("value");
	if (articleVoteUrl != '#') {
		var url = articleVoteUrl+"&r="+score+"&json=true";
		jQuery.ajax(url,
			{
				dataType: 'json',
				success: function(data){
	    			if (data['error'] != null) {
	    				alert(data['error']);
	    			} else {
	    				jQuery("#nw_articleNumberOfVotes_"+articleId).text("("+data['numberOfVotes']+")");
	    				jQuery("#nw_articleAvgScore_"+articleId).attr("value",data['articleAvgScore']);
	    				articleVoteOut(articleId);
	    			}
		  		}
			}
		);
	}
}

function bindArticleVotes() {
	// Bind stars images
	var articleVoteLinks = jQuery('a[id^="nw_articleVoteLink_"]');
	articleVoteLinks.each(function(index,articleVoteLink) {
		var match = /nw_articleVoteLink_(\-?[0-9]+)_([1-5])/.exec(articleVoteLink.id);
		var articleId = match[1];
		var score = match[2];
		jQuery(articleVoteLink).mouseover(function() { articleVoteHover(articleId,score); });
		if (parseInt(articleId) > 0) {
			jQuery(articleVoteLink).click(function() { articleVoteAction(articleId,score); return false; });
		}
	});
	
	// Bind wrapper
	var articleVoteWrappers = jQuery('span[id^="nw_articleVoteWrapper_"]');
	articleVoteWrappers.each(function(index,articleVoteWrapper) {
		var match = /nw_articleVoteWrapper_(\-?[0-9]+)/.exec(articleVoteWrapper.id);
		var articleId = match[1];
		jQuery(articleVoteWrapper).mouseout(function() { articleVoteOut(articleId); });
	});
}

/* Printer Friendly */

function detectPrinterFriendly() {
	if (jQuery("#nw_printer_friendly").attr("value") == "true") {
	   	jQuery(".nw-article-options").html("");
	    var articleDisplayElement = jQuery(".ArticleDisplay");
	    jQuery("#wrapper").html(articleDisplayElement.html());
	    jQuery("#wrapper").css("display", "block");
	    jQuery("*").css("background-color", "#ffffff");
	    document.bgColor = "#ffffff";
	}
}

/* Sharing */

function bindArticleSharing() {
	var articleSharingLinks = jQuery('a[id^="nw_articleSharing_share_"]');
	articleSharingLinks.each(function(index,articleSharingLink) { 
		var match = /nw_articleSharing_share_(\-?[0-9]+)/.exec(articleSharingLink.id);
		var articleId = match[1];
		jQuery(articleSharingLink).click(function() { toggleSharingLinks(articleId); return false; });
	});
	var articleSharingSiteLinks = jQuery('a[id^="nw_articleSharing_site_"]');
	articleSharingSiteLinks.each(function(index,articleSharingSiteLink) { 
		var match = /nw_articleSharing_site_(\-?[0-9]+).*/.exec(articleSharingSiteLink.id);
		var articleId = match[1];
		jQuery(articleSharingSiteLink).click(function() { toggleSharingLinks(articleId); });
	});
	var articleSharingCloseLinks = jQuery('a[id^="nw_articleSharing_close_"]');
	articleSharingCloseLinks.each(function(index,articleSharingCloseLink) { 
		var match = /nw_articleSharing_close_(\-?[0-9]+)/.exec(articleSharingCloseLink.id);
		var articleId = match[1];
		jQuery(articleSharingCloseLink).click(function() { toggleSharingLinks(articleId); return false; });
	});	
}

function toggleSharingLinks(articleId) {
	var linkList = jQuery('#nw_articleSharing_list_'+articleId);
	var articleSharingLink = jQuery('#nw_articleSharing_share_'+articleId);
	var position = jQuery(articleSharingLink).offset();
	var height = jQuery(articleSharingLink).height();
	linkList.css("left", position.left);
	linkList.css("top", position.top+height);
	jQuery('#nw_articleSharing_list_'+articleId).fadeToggle(250);
}

function bindSocialSharing() {
	var socialTriggers = jQuery('a[id^="nw-social-"]');
	socialTriggers.each(function(index,socialTrigger) { 
		jQuery(socialTrigger).fancyZoom();
	});
}

var socialRegExp = new RegExp("nw-social-(facebookLike|googlePlus|tweet|linkedIn)-(0|1|2)");
function detectSharingFromEmail() {
	var anchor = location.hash;
	if (!!anchor) {
		if (socialRegExp.test(anchor)) {
			// Social widgets
			var match = socialRegExp.exec(anchor);
			var site = match[1];
			var param = match[2];
			setTimeout("openSharing('"+site+"',"+param+")", 200);
		} else if (/#nw-share-\d+/.test(anchor)) {
			// Article Sharing
			var articleId = anchor.substring(10);
			setTimeout("toggleSharingLinks("+articleId+")", 1000);
		}
	}
}

function openSharing(site,param) {
	var socialPageUrl = jQuery("#nw-social-pageurl").attr("value");
	var width = 425;
	var height = 140;
	if (site == 'facebookLike') {
		height = 240;
		width = 500;
	}
	jQuery("<a></a>").addClass("iframe").hide().attr("href","sharingFromEmail.html?link="+socialPageUrl+"&param="+param+"&site="+site).fancybox({'width':width, 'height':height, padding:0, margin:0}).click();
}

/* Article Gallery */

function showImage(index) {
	jQuery('div[id^="nw_articleGallery_indexDiv"]').hide();
	jQuery('#nw_articleGallery_indexDiv'+index).show();
	try {
		parent.dyniframesize(parent.document.getElementById('previewPageHtml'));
	} catch(ex) { }
}

function bindArticleGallery() {
	var articleGalleryNavLinks = jQuery('a[id^="nw_articleGallery_"]');
	articleGalleryNavLinks.each(function(index,articleGalleryNavLink) { 
		var match = /nw_articleGallery_[a-z]+_([0-9]+)/.exec(articleGalleryNavLink.id);
		var imageIndex = match[1];
		jQuery(articleGalleryNavLink).click(function() { showImage(imageIndex); return false; });
	});	
}

/* Article comments */
function articleCommentAction(elementId,articleCommentLink) {
	var url = articleCommentLink + "&ajax=true";
	jQuery.ajax(url,
		{
	  		success: function(response){
	    		if(response != 'false'){
	    			var commentsDiv = jQuery('#commentsDiv' + elementId);
	    			commentsDiv.html(response);
					if (commentsDiv.html() != '') {
						window.location.href='#commentsAnchor'+ elementId;
					}
				}
		  	}
		}
	);
}

function postComment() {
	var url = "comments/postComment.html";
	jQuery.ajax(url,
		{
			type:"POST",
			data: jQuery("#nw_comments_form").serialize(),
			dataType: 'json',
			success: function(data){
				var formMessageError = jQuery('#nw_comments_form_message_error');
				formMessageError.hide();
				var formMessageThanks = jQuery('#nw_comments_form_message_thanks');
				formMessageThanks.hide();
				jQuery('#nw_comments_preview').hide();
    			if (data != null && data['error'] != null) {
    				formMessageError.html(data['error']);
    				formMessageError.show();
    			} else {
    				formMessageThanks.show();    				
    				jQuery("#nw_comments_form")[0].reset();
    			}
	  		}
		}
	);
}

function previewComment() {
	var url = "comments/previewComment.html";
	jQuery.ajax(url,
		{
			type:"POST",
			data: jQuery("#nw_comments_form").serialize(),
			dataType: 'json',
			success: function(data){
				var formMessageError = jQuery('#nw_comments_form_message_error');
				formMessageError.hide();
				var commentPreview = jQuery('#nw_comments_preview');
				commentPreview.hide();
    			if (data != null && data['error'] != null) {
    				formMessageError.html(data['error']);
    				formMessageError.show();
    			} else {
    				jQuery('#nw_comments_preview_author').html(data['previewName']);
    				jQuery('#nw_comments_preview_content').html(data['previewContent']);
    				jQuery('#nw_comments_preview_date').html(data['previewDate']);
    				jQuery('#nw_comments_preview').show();
    			}
	  		}
		}
	);
}

function detectArticleComments() {
	var articleCommentsOpcs = jQuery('input[id^="nw_articleComments_opc_"]');
	articleCommentsOpcs.each(function(i,articleCommentsOpc) {
		var match = /nw_articleComments_opc_([0-9]+\-[0-9]+)/.exec(articleCommentsOpc.id);
		var elementId = match[1];
		var viewCommentsLink = jQuery('#nw_articleCommentsUrl_'+elementId).attr("value");
		var opc = jQuery('#nw_articleComments_opc_'+elementId).attr("value");
		var suid = jQuery('#nw_articleComments_suid_'+elementId).attr("value");
		articleCommentAction(elementId,viewCommentsLink+'&opc='+opc+'&s='+suid);
	});
}

/* Surveys */
function bindSurveys() {
	// Paging
	var surveyNavs = jQuery('input[id^="nw_survey_nav_"]');
	surveyNavs.each(function(i,surveyNav) {
		var match = /nw_survey_nav_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)/.exec(surveyNav.id);
		var surveyId = match[1];
		var contentObjectId = match[2];
		var hidePageId = match[3];
		var showPageId = match[4];
		jQuery(surveyNav).click(function() { showSurveyPage('surveyQuestionsPage'+surveyId+'_'+contentObjectId+'_'+hidePageId,'surveyQuestionsPage'+surveyId+'_'+contentObjectId+'_'+showPageId); return false; });
	});
	
	// Click in "Other" input
	var otherQuestions = jQuery('input[name^="questionOther"]');
	otherQuestions.each(function(i,otherQuestion) {
		var match = /questionOther([0-9]+)/.exec(otherQuestion.id);
		var questionId = match[1];
		jQuery(otherQuestion).click(function() { jQuery('input[name="question'+questionId+'"][id*="other"]').attr("checked","checked");});
	});
}

function showSurveyPage(hidePage, showPage) {
	if (hidePage != null && document.getElementById(hidePage) != null) {
		document.getElementById(hidePage).style.display="none";
	}
	if (showPage != null && document.getElementById(showPage) != null) {
		document.getElementById(showPage).style.display="inline";
		window.location.hash=showPage;
		try {
			parent.dyniframesize(parent.document.getElementById('previewPageHtml'));
		} catch(ex) { }					
	}
}

/* Subscribe forms */
function bindSubscribeForms() {
	var subscribeForms = jQuery('form[id^="nw_subscribeBox_form_"]');
	subscribeForms.each(function(i,subscribeForm) {
		jQuery(subscribeForm).submit(function() { return validateSubscribeForm(subscribeForm); });
	});
}

function validateSubscribeForm(subscribeForm){
	try {
		var inputs = subscribeForm.elements;
		var errors = "";
		for (i=0; i<inputs.length; i++) {
			var input = inputs[i];
		    if (input.type != 'hidden' && (input.name.match("^sf_") || input.name.match("^cf_"))) {
				var sfName = input.name.substr(3);
				var inputValue = "";
				if (input.type == "select-one") {
					inputValue = input.options[input.selectedIndex].value;
				} else if (input.type == "select-multiple") {
					for (j=0;j<input.options.length;j++) {
						if (input.options[j].selected) {
							inputValue = input.options[j].value;
						}
					}
				} else {
					inputValue = input.value;
				}
				if (subscribeForm[sfName+"_required"] != null || subscribeForm[input.name+"_required"] != null) {
					if (inputValue == "" || (sfName != null && sfName == "address.country.id" && (inputValue == "0" || inputValue == "-1"))) {
						if (errors != "") { errors += "<br />"; } 
						if (subscribeForm[sfName + "_required_validation_message"] != null ) {
						errors += subscribeForm[sfName + "_required_validation_message"].value;
						} else if (subscribeForm[input.name + "_required_validation_message"] != null) {
						errors += subscribeForm[input.name + "_required_validation_message"].value;
						} else {
						errors += sfName.replace(/\./g," - ") + " is a required field";
						}
					}
				}
			}
		}
		if (errors != "") {
			var subscribeBoxId = subscribeForm['subscribeBoxId'].value;
			var errorsDiv = document.getElementById("subscribeBox"+subscribeBoxId+"errors");
			errorsDiv.innerHTML = errors;
			errorsDiv.style.display = "block";
			return false;
		}
	} catch(ex) { }
	return true;
}


function postSurvey(surveyId,contentObjectId) {	
	var url = jQuery("#surveyForm" + surveyId + "_" + contentObjectId).attr('action');
	jQuery.ajax(url,
		{
			type:"POST",
			data: jQuery("#surveyForm" + surveyId + "_" + contentObjectId).serialize(),
			dataType: 'html',
			success: function(data){
				if (data.indexOf('nw-survey-validation-error') > 0) {;
					document.getElementById("surveyValidationResults" + surveyId + "_" + contentObjectId).innerHTML=data;
					document.getElementById("surveyValidationResults" + surveyId + "_" + contentObjectId).scrollIntoView();				
				} else {
					document.getElementById("surveyResults" + surveyId + "_" + contentObjectId).innerHTML=data;
				}
	  		}
		}
	);
}

function viewSurveyResults(surveyId,contentObjectId,url) {	
	jQuery.ajax(url,
		{
			type:"POST",
			dataType: 'html',
			success: function(data){
				document.getElementById("surveyResults" + surveyId + "_" + contentObjectId).innerHTML=data;
	  		}
		}
	);
}

/* Binders and triggers on load */

jQuery(document).ready(bindArticleVotes);
jQuery(document).ready(bindArticleSharing);
jQuery(document).ready(bindArticleGallery);
jQuery(document).ready(bindSurveys);
jQuery(document).ready(bindSubscribeForms);
jQuery(document).ready(bindSocialSharing);
jQuery(document).ready(detectVotingFromEmail);
jQuery(document).ready(detectSharingFromEmail);
jQuery(document).ready(detectPrinterFriendly);
jQuery(document).ready(detectArticleComments);
