var globalCid;
var globalType;

// ellipsis prob
// One line ellipsis
(function($){
        $.fn.ellipsis = function(optionalWidth){               
                this.each(function(){
                	$(this).css({marginRight: '-10000px'});                             

                	var w;
	                if (!optionalWidth)
	                {
	                	w = $(this).width() - 10000;
	                }
	                else
	                { 
	                	w = optionalWidth;
	                }
	                
	                var t = $(this).html();
	                var length = t.length;
	                var index = 0;
	                var prevChar;	                
	                $(this).html('<span>'+ $(this).html() +'</span>');
	                while (length> 0 && $(this).children().width() >= w) {
	                        // Check if the chop char was html tag and chop it fully
	                        // Assumption no nested tags
	                        if (t.charAt(length - 1) == '>' && length > 2 && (t.charAt(length - 2) == 'b' || t.charAt(length - 2) == 'B')) {
	                        	var ltAmount = 0;
	                        	prevChar = '';

                        		while (ltAmount != 1 && length > 0) {
                        			if (t.charAt(length - 1) == '<' && (prevChar == 'b' || prevChar == 'B')) {
	                        			ltAmount = ltAmount + 1;
	                        		}
	                        		
                        			prevChar = t.charAt(length - 1);
	                        		
		                        	t = t.substr(0, length - 1);	                        
		                        	length = length - 1;
	                        	}
	                        }
	                        else {
	                        	t = t.substr(0, length - 1);	                        
	                        	length = length - 1;
	                        }
	                        
	                        $(this).children().html(t + "...");
	                }
  				});  				
        }
})(jQuery);

// Multi-line ellipsis
(function($){
        $.fn.ellipsisML = function(optionalHeight){
                this.each(function(){
	                var h;
	                
	                if (!optionalHeight)
	                {
	                	h = $(this).height();
	                }
	                else
	                { 
	                	h = optionalHeight;
	                }
	                
	                var t = $(this).html();
	                var length = t.length;	                
	                var index = 0;
	                var prevChar;
	                $(this).html('<span>'+ $(this).html() +'</span>');
	                while (length> 0 && $(this).children().height() > h) {
                        // Check if the chop char was html tag and chop it fully
                        // Assumption no nested tags
                        if (t.charAt(length - 1) == '>' && length > 2 && (t.charAt(length - 2) == 'b' || t.charAt(length - 2) == 'B')) {
                        	var ltAmount = 0;
                        	prevChar = '';
                        	while (ltAmount != 1 && length > 0) {
                        		if (t.charAt(length - 1) == '<' && (prevChar == 'b' || prevChar == 'B')) {
                        			ltAmount = ltAmount + 1;
                        		}
                        		
                        		prevChar = t.charAt(length - 1);
                        		
	                        	t = t.substr(0, length - 1);	                        
	                        	length = length - 1;
                        	}
                        }
                        else {
	                        t = t.substr(0, length - 1);
	                        length = length - 1;
	                    }
	                    
                        $(this).children().html(t + "...");
	                }
	            });
        }
})(jQuery);

function chopSmartTakeExtraIfBolded(text, newLength) {
	retVal = text.substr(0, newLength);
	nextLTPos = text.indexOf("<", newLength);
	
	// Take the sentence until the end of the closing tag
	if (nextLTPos > 0 && text.charAt(nextLTPos + 1) == '/') {
		retVal = retVal + text.substr(newLength, nextLTPos + 3 - newLength + 1);
	}
	
	return retVal;
}

function sendingPage(postFix) {
	$('.emailSendingMessage' + postFix).show();
	$('.emailBody' + postFix).hide();
}

function sendProject(postFix) {
	sendProjectPageType(postFix);
}

function createMailRequest(fromEmail, toEmail, mailComments) {
	var CallParams = {}; 
	CallParams.type = "POST"; 
	CallParams.url = subfolder + "/sendMail"; 
	CallParams.processData = true; 
	
	if (globalType == 0) {
		CallParams.data = {type: "0", from: fromEmail, to: toEmail, comments: mailComments, cid: globalCid};
		fGoogleEvent('sendProjectMail','c=' + globalCid);
	}
	else {
		CallParams.data = {type: "1", from: fromEmail, to: toEmail, comments: mailComments, q: query};
		joinJSONProp(CallParams.data, filtersJSON);
		fGoogleEvent('sendQueryMail','q=' + escape(query));
	}
	
	CallParams.dataType = "json"; 
	
	return CallParams;
}

function sendAgain(elem) {
	var rootElement = $(elem).parents(".shareprjcont");
	rootElement.find(".emailSendingMessage").hide();
	rootElement.find(".mailForm").show();
	rootElement.find(".emlTo").val("");
}

function sendProjectPageType(postFix, index) {
	var CallParams;
	var isValid = false;
	var usrEmail;
	if (postFix == "3") {
		var formArray = ['.emlFrom','.emlTo'];
		var rootElement = $(".shareprjcont").eq(index);
		if(validateEmails(rootElement,formArray,postFix)) {
			isValid = true;
			rootElement.find(".emailSendingMessage").html("Sending Email...").show();
			rootElement.find(".mailForm").hide();
			
			usrEmail = rootElement.find('.emlFrom').val();
			CallParams = createMailRequest(usrEmail, rootElement.find('.emlTo').val(), ''); 
			
			CallParams.success = function(data) {
				if (data.status == "ok") {
					rootElement.find(".emailSendingMessage").html('This message will be sent to <strong><span>' + rootElement.find('.emlTo').val() + '</span></strong> shortly<br/><a href="#" onclick="sendAgain(this); return false;">Send another email</a>').show();
				}
				else {					
					alert("Error occured while trying to send the mail. please try again");
				}
			};			 
		}
	} else {		
		var formArray = ['#nameTxt' + postFix,'#emailTxt' + postFix];
		
		if(validateEmails($("#emailBox" + postFix),formArray,postFix)) {
			isValid = true;
			sendingPage(postFix);
			
			usrEmail = $('#nameTxt' + postFix).val();
			CallParams = createMailRequest(usrEmail, $('#emailTxt' + postFix).val(), $('#commentTxt' + postFix).val()); 
			
			CallParams.success = function(data) {
				if (data.status == "ok") {
					$('.emailBoxHead').find('h3').html('Email sent successfully');
					$('.emailSentMessage' + postFix).find('span').eq(0).html($('#emailTxt' + postFix).val());
					$('.emailSentMessage' + postFix).show();
					$('.emailSendingMessage' + postFix).hide();
				}
				else {
					alert("Error occured while trying to send the mail. please try again");
				}
			};			 
		}
	}
	
	if (isValid)
	{
		$.cookie("registerEmail", usrEmail, { expires: 3650, path: '/' });
		
		CallParams.error = function() {
			alert("Error occured while trying to send the mail. please try again");
		};
		 
		$.ajax(CallParams);
	}
}


function addEmptyAjax(url) {
	if (url.indexOf('#') == -1)
		url = url + "#nf=1";
	
	return url;
}

function removeEmptyAjax(url) {
	return removeParam(url, 'nf');
}

function triggerFixRangeChange() {
	
	var wholeNumberRegex = /^[0-9]+$/;
	var newURL = getFullWindowURL();
	
	if (!isEmpty($('#fixmax').val()) && $('#fixmax').val() != 'Max') {
		newURL = removeEmptyAjax(addFilterParamToSpecificURL(newURL, 'maxfr', $('#fixmax').val(), 'maxfr'));
	}
	else {
		newURL = removeParam(newURL, 'maxfr');
	}

	if (!isEmpty($('#fixmin').val()) && $('#fixmin').val() != 'Min') {
		newURL = removeEmptyAjax(addFilterParamToSpecificURL(newURL, 'minfr', $('#fixmin').val(), 'minfr'));
	}
	else {
		newURL = removeParam(newURL, 'minfr');		
	}
			
	window.location.href = addEmptyAjax(removeParam(removeCampaignParams(removePage(newURL)), 'ffx'));	
}

function triggerHourRangeChange() {
	
	var wholeNumberRegex = /^[0-9]+$/;
	var newURL = getFullWindowURL();
	
	if (!isEmpty($('#hourmax').val()) && $('#hourmax').val() != 'Max') {
		newURL = removeEmptyAjax(addFilterParamToSpecificURL(newURL, 'maxhr', $('#hourmax').val(), 'maxhr'));
	}
	else {
		newURL = removeParam(newURL, 'maxhr');
	}
	
	if (!isEmpty($('#hourmin').val()) && $('#hourmin').val() != 'Min') {
		newURL = removeEmptyAjax(addFilterParamToSpecificURL(newURL, 'minhr', $('#hourmin').val(), 'minhr'));
	}
	else {
		newURL = removeParam(newURL, 'minhr');		
	}
					
	window.location.href = addEmptyAjax(removeParam(removeCampaignParams(removePage(newURL)), 'fhr'));
}

function docReady() {
	initSearchBar();

	$(".dualBoxFix").focus(function(e) {
		$('.fixGo').removeClass("dispnone");
		$('#dualboxesFix').addClass('highlighBox');
	});
			
	$(".dualBoxFix").blur(function(e) {
		$('.fixGo').addClass("dispnone");
		$('#dualboxesFix').removeClass('highlighBox');		
	});

	$(".dualBoxHour").focus(function(e) {
		
		$('.hourGo').removeClass("dispnone");
		$('#dualboxesHour').addClass('highlighBox');
	});
	
	$(".dualBoxHour").blur(function(e) {		
		
		$('.hourGo').addClass("dispnone");
		$('#dualboxesHour').removeClass('highlighBox');								
	});
	
	// Slider part - only if filter exist in the page
	if ($('#filterColumn').length > 0) {
		$('#fixRateSlider').slider({
			range: "min",
			value: eval(getParam('ffx', '0')),
			min: 0,
			max: 4,
			slide: function(event, ui) { setFixRateText(ui.value); },
			start: function(event, ui) { fixRateOldVal = ui.value; },
			change: function(event, ui) { 
				if (fixRateOldVal != ui.value) { 
					if (ui.value == 0) {
						window.location.href = addEmptyAjax(removeParam(removeCampaignParams(removePage(getFullWindowURL())), 'ffx'));
					}
					else {
						window.location.href = removeEmptyAjax(removeParam(removeParam(removePage(addFilterParam('ffx', ui.value, 'ffx')),'minfr'),'maxfr'));
					}
				}
			}			
		});
		
		setFixRateText($('#fixRateSlider').slider('option', 'value'));
				
		$('#hrRateSlider').slider({
			range: "min",
			value: eval(getParam('fhr', '0')),
			min: 0,
			max: 5,
			slide: function(event, ui) { setHourlyRateText(ui.value); },
			start: function(event, ui) { hrRateOldVal = ui.value; },
			change: function(event, ui) { 
				if (hrRateOldVal != ui.value) { 
					if (ui.value == 0) {
						window.location.href = addEmptyAjax(removeParam(removeCampaignParams(removePage(getFullWindowURL())), 'fhr'));
					}
					else {
						window.location.href = removeEmptyAjax(removeParam(removeParam(removePage(addFilterParam('fhr', ui.value, 'fhr')),'minhr'),'maxhr'));
					}
				}
			}
		});

		setHourlyRateText($('#hrRateSlider').slider('option', 'value'));
		
		if ($('#timeleftSlider').length > 0) {
			$('#timeleftSlider').slider({
				range: "min",
				value: eval(getParam('ftl', '-1')) + 1,
				min: 0,
				max: 4,
				slide: function(event, ui) { setTimeLeftText(ui.value); },
				start: function(event, ui) { timeleftOldVal = ui.value; },
				change: function(event, ui) {
					if (timeleftOldVal != ui.value) {
						if (ui.value == 0) {
							window.location.href = addEmptyAjax(removeParam(removeCampaignParams(removePage(getFullWindowURL())), 'ftl'));
						}
						else {
							window.location.href = removeEmptyAjax(removePage(addFilterParam('ftl', ui.value - 1, 'ftl')));
						}
					}
				}			
			});
			
			setTimeLeftText($('#timeleftSlider').slider('option', 'value'));
		}
		
		if ($('#postSlider').length > 0) {
			$('#postSlider').slider({
				range: "min",
				value: eval(getParam('fcd', '-1')) + 1,
				min: 0,
				max: 4,
				slide: function(event, ui) { setPostDateText(ui.value); },
				start: function(event, ui) { postdateOldVal = ui.value; },
				change: function(event, ui) {
					if (postdateOldVal != ui.value) {
						if (ui.value == 0) {
							window.location.href = addEmptyAjax(removeParam(removeParam(removeCampaignParams(removePage(getFullWindowURL())), 'fcd')));
						}
						else {
							window.location.href = removeEmptyAjax(removePage(addFilterParam('fcd', ui.value - 1, 'fcd')));
						}
					}
				}			
			});
			
			setPostDateText($('#postSlider').slider('option', 'value'));
		}
	}
	
	$('a.external_link').click( function() { 
		window.open(this.href);  
		return false; 
	});
	
	$('#mailTB').keypress(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
 		if(code == 13) { //Enter keycode
			processEmailAlerts();
			e.preventDefault();
 		}
	});
	$('#submitEmailAlert').click(function(){ processEmailAlerts(); });
	
	$("#paging a").click(function() { $(window).scrollTop(0); });
	
	$(".ellipsisML").ellipsisML();	
	
	$('.ui-slider-handle').show();
	
	$('#filterSectionContent h4').each(function(index){
		$(this).find('a').click(function(){						   
			if($(this.parentNode).hasClass('blackHeadingOpen')){
				$('.showFilterSection').eq(index).hide();
				$(this.parentNode).removeClass('blackHeadingOpen').addClass('blackHeadingClosed');
				if ($($(this.parentNode).children()[0]).hasClass('treenode'))
					$($(this.parentNode).children()[0]).html('&nbsp;►'); 
			}else if($(this.parentNode).hasClass('blackHeadingClosed')){
				$('.showFilterSection').eq(index).show();
				$(this.parentNode).removeClass('blackHeadingClosed').addClass('blackHeadingOpen');
				if ($($(this.parentNode).children()[0]).hasClass('treenode'))
					$($(this.parentNode).children()[0]).html('&nbsp;▼');
			}

			$.cookie($(this).attr("id"), $.cookie($(this).attr("id")) != null ? null : "1", { expires: 3650, path: '/' });				
						
			return false;
		});		  
	});
	
	$('.projobj').hover(function() {$(this).addClass("projobjhov"); }, function() {$(this).removeClass("projobjhov"); });
		
	$('.share').click(function(){
		var cont = $(this).parents('.projobj').find('.shareprjcont');
		if(!cont.is(':visible')){
			$(this).parents('.projobj').find('.moretlscont').hide();
			$(this).parents('.projobj').find('.moretls').removeClass('moretlsopn').parent().removeClass('tab2open');
			$(this).parents('.projobj').find('.sitecont').hide();
			$(this).parents('.projobj').find('.site').parent().removeClass('tab0open');
			
			cont.show();
			$(this).parent().addClass('tab1open');
			fGoogleEvent('shareTools','');
			
			if (cont.find('.emlFrom').val() == "" && $.cookie("registerEmail") != null)
				cont.find('.emlFrom').val($.cookie("registerEmail"));
		} else {
			cont.hide();
			$(this).parent().removeClass('tab1open');
			
			if ($.cookie("registerEmail") != null && cont.find('.emlFrom').val() == $.cookie("registerEmail"))
				cont.find('.emlFrom').val("");			
		}
	});
	$('.closeshare2').click(function() {
		var cont = $(this).parents('.projobj').find('.shareprjcont');
		var share = $(this).parents('.projobj').find('.share');
		cont.hide();
		share.parent().removeClass('tab1open');
		return false;
	});
	$('.shareprojph li a').click(function() {
		if ($(this).attr("class") != "stEmail") {
			window.open(subfolder + "/sharer?c=" + $(this).attr('href').substring(1) + "&st=" + $(this).attr("class"));
			fGoogleEvent("msg" + $(this).attr("class").substring(2),'c=' + $(this).attr('href').substring(1));
		}
		return false;
	});	
					
	$('.seeMore').each(function(index){
		$(this).click(function(){		 
			$(this).parent().find('.more').show();
			$(this).hide();
			
			return false;
		});		  
	})
		
	if ($('.tooltip').length > 0) {
		$('.tooltip').tooltip({ 
		    track: true, 
		    delay: 0, 
		    bodyHandler: function() {
		    	if ($(this).hasClass('next')) { 
		        	return $(this).next().html();
		        }
		    	else if ($(this).hasClass('contest')) { 
		        	return $("#contest").html();
		        }
		    	else if ($(this).hasClass('bidding')) { 
		        	return $("#bidding").html();
		        }
		        else {
		        	return $(this).parent().next().html();
		        } 
		    }, 
		    showURL: false, 
		    fade: 250,
			top: 5, 
	    	left: 5,
	    	extraClass: "maxWidth"
		});
	}

	if ($('.buyersectooltip').length > 0) {
		$('.buyersectooltip').tooltip({ 
		    track: true, 
		    delay: 200, 
		    bodyHandler: function() {	
				var propCount = $(this).next().find("span").length;
				var height = 135 - (30 * (4 - propCount)) - 20 * 2;
				return "<div style='margin-top:" + (95 - height) + "px;height:" + height + "px;width:161px;padding:20px;overflow:hidden;background:url(/images/buyerfacts.png) no-repeat;'>" + $(this).next().html().replace(/<\/span>[^<^>]*<span>/gmi, "</span><div class='propsep'></div><span>") + "</div><div style='height:33px;width:201px;background:url(/images/buyerfacts.png) no-repeat left bottom;'></div>"
		    }, 
		    showURL: false, 
		    positionLeft: true,
		    fade: 0,
			top: -180, 
	    	left: 150,
	    	extraClass: "transp byrinfo"
		});
	}
	
	$("#addMsg").click(function() {
		if ($(this).hasClass("bullet")) {
			$(this).addClass("bulletdown").removeClass("bullet");
		} else {
			$(this).addClass("bullet").removeClass("bulletdown");
		}
		$(this).next().next().toggle();
		
		return false;
	});
	
	$("#sendMail").click(function() {
		globalType = 0;
		globalCid = mainCID;
		sendProjectPageType("2");
		return false;
	});

	$("#sendMail2").click(function() {
		globalType = 1;
		sendProjectPageType("2");
		return false;
	});
	
	$('#sendEmailAgain2').click(function(){
		$('#emailTxt2').val('');	 
		$('.emailSentMessage2').hide();
		$('.emailBody2').show();
		
		return false;
	});	
	
	$(".shrbut").click(function() {
		var index = $(".shrbut").index($(this));
		globalType = 0;
		globalCid = $(".shareprjcont").eq(index).find("li.selected a").attr('href').substring(1);
		sendProjectPageType("3", index);
	});
	
	$('.filterGroup .row label').hover(function(){
		$(this).css('text-decoration','underline');
	} , function(){
		$(this).css('text-decoration','none');
	});
	
	$('.sharetab .share').hover(function(){
		$(this).css('text-decoration','underline');
	} , function(){
		$(this).css('text-decoration','none');
	});	
	
	$(".fblikethisurl").each(function(index, value) {
		if ($(value).html() == '') {
			var width = ($(value).hasClass('full') ? '190' : '100');
			var hght = ($(value).hasClass('full') ? '40' : '21');						
			
			$(value).append('<iframe src="http://www.facebook.com/plugins/like.php?href=' + escape(window.location.href) + '&amp;locale=en_US&amp;layout=' + ($(value).hasClass('full') ? 'standard' : 'button_count') + '&amp;show_faces=false&amp;width=' + width + '&amp;action=like&amp;font&amp;colorscheme=light&amp;height=' + hght + '" scrolling="no" frameborder="0" allowtransparency="true" style="border:none;overflow:hidden;width:' + width + 'px;height:' + hght + 'px;"></iframe>');
		}
	});		
}

$(document).ready(function(){
	docReady();
	
	jQuery("#fullMovie").dialog({ position: 'center', autoOpen: false, height: 381, width: 429, modal: true, show: 'fade', hide: 'fade', beforeclose: function(event, ui) { $('.fullMovieBody').html(''); }});
	jQuery("#emailBox").dialog({ position: 'center', autoOpen: false, height: 350, width: 345, modal: true, show: 'fade', hide: 'fade' });

	$('#nameTxt').keypress(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
 		if(code == 13) { //Enter keycode
			sendProject("");
			e.preventDefault();
 		}
	});
	$('#emailTxt').keypress(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
 		if(code == 13) { //Enter keycode
			sendProject("");
			e.preventDefault();
 		}
	});
	
	$('#sendProject').click(function(){		 
		sendProject("");
		return false;
	});
	
	$('#sendEmailAgain').click(function(){
		$('#emailTxt').val('');	 
		$('.emailSentMessage').hide();
		$('.emailBody').show();
		
		return false;
	});
	
	$(".fblike").each(function(index, value) {
		if ($(value).html() == '') {
			var width = ($(value).hasClass('full') ? '175' : '100');
			var hght = ($(value).hasClass('full') ? '40' : '21');
			$(value).append('<iframe src="http://www.facebook.com/plugins/like.php?href=' + escape("http://www.donanza.com/") + '&amp;layout=' + ($(value).hasClass('full') ? 'standard' : 'button_count') + '&amp;show_faces=false&amp;width=' + width + '&amp;action=like&amp;font&amp;colorscheme=light&amp;height=' + hght + '" scrolling="no" frameborder="0" allowtransparency="true" style="border:none;overflow:hidden;width:' + width + 'px;height:' + hght + 'px;"></iframe>');
		}
	});
	
	logQuery();
});

function logQuery() {
	if (!isWL() && typeof(query) != 'undefined' && query != '') {
		doLog({a:'qry', q:query});
	}
}

function emailAlerts() {
	if ($("#mailAlerts").hasClass('openedForMail')){
		$("#mailAlerts").addClass('closedForMail').removeClass('openedForMail');
		$("#mailAlertForm").hide();
	}
	else {
		var currentMail = $('#mailTB').val();
		
		if ((currentMail == '' || currentMail == 'Enter your mail') && $.cookie("registerEmail") != null) {
			$('#mailTB').val($.cookie("registerEmail"));
		}
		
		$("#mailAlerts").addClass('openedForMail').removeClass('closedForMail');
		$("#mailAlertForm").show();
	}	
}

function loadMovie(element, title, url){	
	element.html('<span class="videoTitle dispnone">' + title +'</span><span class="videoUrl dispnone">' + url +'</span><img height="161" width="215" src="' + getFirstImage(url)  + '" /><div style="margin-top: -100px; margin-right: 77px; text-align: right;"><img src="/images/youtube-play.jpg"/></div>');	
}

function setFixRateText(value){
	var valArr = ["Any","More than $100","More than $500","More than $1000","More than $10000"];
	$("#budgetOrReward .slider").eq(0).find('h3').html(valArr[value]);
}

function setHourlyRateText(value){
	var valArr = ["Any","More than $10/hr","More than $15/hr","More than $20/hr","More than $30/hr","More than $40/hr"];
	$("#budgetOrReward .slider").eq(1).find('h3').html(valArr[value]);
}

function setTimeLeftText(value){
	var valArr = ["Any","1 day or less","Between 1-3 days","Between 3-7 days","More than 7 days"];
	$("#timeLeft .slider").find('h3').html(valArr[value]);
}

function setPostDateText(value){
	var valArr = ["Any","1 day or less","Last 3 days","Last 7 days","Last 30 days"];
	$("#postDate .slider").find('h3').html(valArr[value]);
}		

function getParam(name, defaultValue) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&#]"+name+"=([^&#]*)");
  var results = regex.exec(getFullWindowURL());
  
  return (results == null ? defaultValue : results[1]);
}

function removePage(url) {
	return removeParam(url, "p");
}

function removeParam(url, paramName){
	retVal = url.replace(new RegExp(paramName + '=\\d+&|&' + paramName +'=\\d+|' + paramName +'=\\d+', 'i'), '');
	retVal = retVal.replace("&&", "&").replace("?#","#");
	
	
	if (retVal.indexOf("#") > 0 && retVal.indexOf("#") == retVal.length - 1) {
		retVal = retVal.substr(0, retVal.length - 1);
	}
	
	return retVal;
}

function removeStringParam(url, paramName){
	retVal = url.replace(new RegExp(paramName + '=\\w+&|&' + paramName +'=\\w+|' + paramName +'=\\w+', 'i'), '');
	retVal = retVal.replace("&&", "&").replace("?#","#");
		
	if (retVal.indexOf("#") > 0 && retVal.indexOf("#") == retVal.length - 1) {
		retVal = retVal.substr(0, retVal.length - 1);
	}
	
	return retVal;
}

function removeCampaignParams(url) {
	return removeStringParam(removeStringParam(removeStringParam(url, "utm_source"), "utm_medium"), "utm_campaign"); 
}

function addFilterParamToSpecificURL(url, paramName, paramValue, paramToRemoveName){
	var currUrl = removeCampaignParams(url);
	var prefix = "";
	
	currUrl = removeParam(removeParam(currUrl, paramToRemoveName), paramName);
	prefix = (currUrl.indexOf("#") > 0 ? "&" : "#"); 
	
	return currUrl + prefix + paramName + "=" + paramValue;	
}

function addFilterParam(paramName, paramValue, paramToRemoveName){
	var currUrl = removeCampaignParams(getFullWindowURL());
	var prefix = "";
	
	currUrl = removeParam(removeParam(currUrl, paramToRemoveName), paramName);
	prefix = (currUrl.indexOf("#") > 0 ? "&" : "#"); 
	
	return currUrl + prefix + paramName + "=" + paramValue;	
}

function validateEmails(rootElement, formArray, postFix){
	var isValid = true;
	var messageArray = ['Please enter a valid Email address','Please enter a valid Email address'];
	
	for(var i=0; i<formArray.length; i++){
		str = rootElement.find(formArray[i]).val();
		if(validateEmailString(str)){		
			rootElement.find('em').eq(i).html('&nbsp;');	
		}else{
			rootElement.find('em').eq(i).html(messageArray[i] + (postFix == "2" ? "<br/>" : ""));	
			isValid = false;
		}
	}
	
	return isValid;
}

function getFirstImage(url, size) {
	if(url === null){ return ""; }
		
	if (url.indexOf("http://www.youtube.com/v/") != 0)
		return "/images/movie.jpg";
	
	size = (size === null) ? "big" : size;
	var vid;
	var results;
	
	var index = url.lastIndexOf("/");
	
	vid = ( index == -1 ) ? url : url.substr(index + 1);
	
	index = vid.indexOf("?");
	
	if (index != -1)
		vid = vid.substr(0, index);
	
	if(size == "small"){
		return "http://img.youtube.com/vi/" + vid + "/2.jpg";
	}else {
		return "http://img.youtube.com/vi/" + vid + "/0.jpg";
	}
}

function joinJSONProp(srcJSON, morePropJSON) {
	for (var key in morePropJSON) {
	  if (morePropJSON.hasOwnProperty(key)) {
	    srcJSON[key] = morePropJSON[key];
	  }
	}
}

function processEmailAlerts() {
	var mailString = $("#mailTB").val();
	if (validateEmailString(mailString)) {
		$('#submitEmailAlert').attr("disabled", "disabled");
		$('#msg').text('Processing request, please wait...');
		$('#msg').removeClass('error');
		
		$.cookie("registerEmail", mailString, { expires: 3650, path: '/' });

		var CallParams = {}; 
		CallParams.type = "POST"; 
		CallParams.url = subfolder + "/registerMailAlerts"; 
		CallParams.processData = true; 
		CallParams.data = {m: mailString, q: query};
		joinJSONProp(CallParams.data, filtersJSON);
		fGoogleEvent('registerMailAlerts','m=' + mailString + '&q=' + escape(query));
		
		CallParams.dataType = "json"; 
		
		CallParams.success = function(data) {
			if (data.status == "ok") {
				$("#mailTB").css('display','none');
				$("#submitEmailAlert").css('display','none');
				$('#msg').html('<strong>Please check your email. We have sent a confirmation message.</strong><br/>Approve it and start receiving emails with project alerts.');
			}
			else if (data.status == "exists") {
				$('#msg').html("Mail address already has a email alert for this search");
				$('#msg').addClass('error');				
				$('#submitEmailAlert').removeAttr("disabled");
			}
			else {
				$('#msg').html("Error occured while trying to send the mail. please try again");
				$('#msg').addClass('error');
				$('#submitEmailAlert').removeAttr("disabled");
			}
		};
		 
		CallParams.error = function() {
			$('#msg').html('Error occured while trying to register to mail alerts. please try again');
			$('#msg').addClass('error');
			$('#submitEmailAlert').removeAttr("disabled");
		};
		 
		$.ajax(CallParams); 				
	}
	else {
		$('#msg').html('Please enter a valid mail');
		$('#msg').addClass('error');
	}
}

$().ready(function() {
	if (ajaxEnabled)
		setInterval("checkSearchAjax()", 300);
});
  
var currSearchFilters = "";
var firstEmptyParamPV = true;

function hideLoading() {
	$("#loading").hide();
}

function showLoading() {
	$("#loading").show();
}

function goAjax(elementId) {
	setTimeout('window.location.href = addEmptyAjax(document.getElementById("' + elementId + '").href);', 300);
}

function sendPageView() {
	if (isWL()) {
		if (query == "") {
			var pvPage = window.location.href.substring(window.location.href.indexOf('/', 9) + 1);
			pvPage = pvPage.replace("#nf=1", "");
			if (pvPage.indexOf("#") != -1) {
				pvPage = pvPage.replace("#", (pvPage.indexOf("?") != -1 ? "&" : "?"));
			}
			dnzPTracker._trackPageview('/' + wlUser + '/' + pvPage);
		} else {
			dnzPTracker._trackPageview('/' + wlUser + '/search?' + "q=" + escape(query) + getHashParamsSupportEmpty());
		}
	} else {
		dnzPTracker._trackPageview('/search?' + "q=" + escape(query) + getHashParamsSupportEmpty());
	}
}

function getHashSupportEmpty() {
	return (document.location.hash == "#nf=1") ? "" : document.location.hash;
}

function getHashParamsSupportEmpty() {
	return getHashParams().replace(new RegExp('nf=1&|&nf=1|nf=1', 'i'), '');
}

function checkSearchAjax() {
	if (currSearchFilters != getHashSupportEmpty()) {
		currSearchFilters = getHashSupportEmpty();
		firstEmptyParamPV = false;
		
		showLoading();		
		$.get(subfolder + "/searchajax", "qr=" + escapeQuery(query) + getHashParamsSupportEmpty(), function(data) {  
			$(isWL() ? "#ajaxPart" : "#mainContainer").html(data);
			docReady();
			hideLoading();
			sendPageView();
		});  
	} else if (currSearchFilters == "" && firstEmptyParamPV) {
		var page = "";
		firstEmptyParamPV = false;
		hideLoading();
		sendPageView();
	}
}
