var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
var globalCid;
var globalQuery;

// 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;
	                $(this).html('<span>'+ $(this).html() +'</span>');
	                while (length > 0 && $(this).children().width() >= w) {
	                        t = t.substr(0, length - 1);
	                        $(this).children().html(t + "...");
	                        length = length - 1;
	                }
  				});  				
        }
})(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;	                
	                $(this).html('<span>'+ $(this).html() +'</span>');
	                while (length > 0 && $(this).children().height() >= h) {
                        t = t.substr(0, length - 1);
                        $(this).children().html(t + "...");
                        length = length - 1;
	                }              
	            });
        }
})(jQuery);

/*
 * jQuery UI fade effect, based on pulsate
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Depends:
 *	effects.core.js
 */
(function($) {
	$.effects.fade = function(o) {
		return this.queue(function() {
			// Create element
			var el = $(this);
	
			// Set options
			var speed = 500;
			var mode = o.options.mode || 'show'; // Set Mode
	
			// Animate
			if (mode == 'show') {
				el.fadeIn(speed);
			} else {
				el.fadeOut(speed);
			};
			el.queue('fx', function() { el.dequeue(); });
			el.dequeue();
		});
	}
})(jQuery);

// Marketing slogan
var rollovertimer = 0;
var index =0;
var number = 0;

$(function(){
$.getJSON("getMarketingSlogansJSON", 
	function(data){
		  html = '';
          $.each(data, function(i,item){
		   html += '<div class="topbannertxt">'+item.slogan+'</div>';
		  });
		  $("#s1").html(html);
		  $('#s1').cycle({fx: 'fade', timeout: 15000, random: 1});
	});
});

// Category area & project rotator
var cycleProjects = function() { 
	$('#s4').cycle({ 
		timeout:14000,
		speed:1000,
		pause:1,
		fx:'scrollHorz',
		pager:'#pager',
		prev:'#prev',
		next:'#next',
		easing:'easeOutCubic',
		pagerAnchorBuilder:pagerFactory
	});
}

function pagerFactory(idx, slide) {
	var s = idx > 4 ? ' style="display:none"' : '';
	if(idx == slide){
		clas = "active";
	}
	else {
		clas = "deactive";
	}
    return '<li '+s+'><a href="#" class="'+clas+'" onclick="fGoogleEvent(\'offerProjectButton\',\'\');"></a></li>';
};

   // Render JSON projects
   function renderProjects(data){
	  html = '';
	  linkType = 'external_link';
	  
	  if ($.cookie("open") == "same"){
	  	linkType = 'internal_link';
	  }
	  
        $.each(data, function(i,item){			
		    iconImg = '';
		    titleClass = 'clngTitle';
		    cuttedTitle = item.title;
		    cuttedDesc = item.description;
		    
			/*if (item.is_bidding == true) {
				iconImg = 'biddingImg';
			}
			else if (item.is_competition == true) {
				iconImg = 'contestImg';
			}
			else {
				titleClass = 'clngTitleNoIcon';
			}*/
			
			titleClass = 'clngTitleNoIcon';
			
			if (cuttedTitle.length > 55) {
				cuttedTitle = cuttedTitle.substr(0, 55) + "...";
			}
			
			if (cuttedDesc.length > 110) {
				cuttedDesc = cuttedDesc.substr(0, 110) + "...";
			}
			
			convLink = 'go?u=' + escape(item.url) + '&s=' + item.site_name + '&r=' + (i + 1) + '&c=' + item.id + '&q2=' + escape(globalQuery) + '&src=0';
		    html += '<div><div class="rightboxtop"><div class="rightboxtopL ' + iconImg + ' left"><a class="nounderline ' + linkType + '" href="' + convLink + '" onclick="pageViewAnchor(this);"><h4 class="ellipsisML ' + titleClass + '" title="' + item.title + '">' + cuttedTitle + '</h4></a><div><span class="credate">from </span><span class="sitename">' + item.site_name + '</span></div></div></div><div class="rightboxcontent"><div class="wdth225 mB5"><p class="font13 ellipsisML descHeight" title="' + item.description + '">' + cuttedDesc + '</p></div><div class="wdthpercent100" style="height:65px; overflow:hidden;"><ul><li class="reward"><p><img src="images/reward.v1.gif" alt="Reward" align="left" class="pR10" /></p><div class="rewardText"><p class="ellipsis">'+item.reward+'</p></div></li><li class="deadline">' + (item.deadline == '' ? '&nbsp;' : '<p><img src="images/clock1.gif" alt="Timeleft" align="left" class="pR13 pL3 pB6" title="Time left ' + (item.is_bidding ? 'to bid' : 'to deliver') + '"/></p><p>'+item.deadline+'</p>') + '</li></ul></div><div class="wdthpercent100" style="height:56px; overflow:hidden;"><div class="left pT13"><div class="projectbtnbox"><a href="' + convLink + '" onclick="pageViewAnchor(this);" title="Do It" class="projectbtn ' + linkType + '"></a></div></div><div class="boxinfo left"><a href="' + item.perm_link + '" class="info">More info</a><br /><a href="#' + item.id + '" class="share">Email</a></div></div><div class="clear"></div></div></div>';
        });
		
		if (html == '') {
			html = '<div><div class="rightboxtop"><div class="rightboxtopL left"></div></div><div class="rightboxcontent"><div class="wdth225 mB5"><p class="font13 descHeight">Oops... no projects were found, please try again</p></div></div></div>';
	    	$("#s4").html(html);
		}
		else {			  
		    $("#s4").html(html);
		    
			$('#s4 a.external_link').click(function() { 
				window.open(this.href);  
				return false; 
			});
		    
		    addEmailFunc();
		    $("#s4 .ellipsis").ellipsis(187);
		    $(".ellipsisML").ellipsisML();
			$('#pager').html('');
			$('#s4').height($('#s4').children(':first').height());
			cycleProjects();
		}
   }
   
   function addEmailFunc(){
	$('.share').click(function(){		 			
		var url = $(this).attr('href');
		globalCid = url.substring(url.indexOf('#') + 1);
		
		$('#emailTxt').val('');
		$('#commentTxt').val('Hi,\nWhile searching for online projects on donanza.com, I came across an online project that I think you might find interesting. Check it out.');			
		$("#emailBox").find('em').html('&nbsp;');
					
		$('.emailSentMessage').hide();
		$('.emailSendingMessage').hide();
		$('.emailBody').show();
		
		$('#s4').cycle('pause');
		
		jQuery('#emailBox').show();
		jQuery('#emailBox').dialog('open');
		$(".ui-widget-overlay").css({"opacity": "0.05"});
		
		if (validateEmailString($("#nameTxt").val())) {
			$("#emailTxt").focus();
		}
		else {
			$("#nameTxt").focus();
		}
		
		return false;
	});
   }
   
   // Get category projects
   var getCatData =function(catid){
   			linkObj = $("#cat_" + catid + " h6 a:first");
   			setLoadingIcon(linkObj.text());
   			url = linkObj.attr('href');
   			url.match(/\/jobs\/(.*?)($|\?)/);
   			globalQuery = RegExp.$1;
			$.getJSON("getCloudCategoryProjectsJSON",
			{ c: catid },
			renderProjects
        );		
	};

   // Get recent search projects
   var getRSData =function(query){			
   			setLoadingIcon('');
   			globalQuery = query;
			$.getJSON("getProjectsForRecentSearchJSON",
			{ q: query },
			renderProjects
        );		
	};
				
   //var randtimer;
   var slideshow;
   var element;
   
$(document).ready(function(){				
	jQuery("#emailBox").dialog({ position: 'center', autoOpen: false, height: 350, width: 345, modal: true, show: 'fade', hide: 'fade', beforeClose: function(event, ui) { $('#s4').cycle('resume'); } });

	// Category hovering + auto move category	
				
	// Category\RS hovering
	$('#hover-demo .txtdiv').hover(function() {
		$(this).addClass('txtdivFollower');
		if (!$(this).hasClass("txtdivHover")) {
			var catId = $(this).attr('id').substring(4);
			//clearInterval(randtimer);
			element = this;
			slideshow = setTimeout(function(){			
				$('#hover-demo .txtdivHover').addClass('txtdiv').removeClass('txtdivHover');			
				$(element).addClass('txtdivHover');
				$(element).removeClass('txtdiv');
				getCatData(catId);
			},300);
		}        
      }, function() {
      	$(this).removeClass('txtdivFollower');
		clearTimeout(slideshow);
      });

      $('#hover-demo .rsBox').hover(function() {
		$(this).addClass('rsBoxFollower');
      	if (!$(this).hasClass("rsBoxHover")) {
			var q = $("a:first", this).attr('title');
			//clearInterval(randtimer);
			element = this;
			slideshow = setTimeout(function(){			
				$('#hover-demo .rsBoxHover').addClass('rsBox').removeClass('rsBoxHover');			
				$(element).addClass('rsBoxHover');
				$(element).removeClass('rsBox');
				getRSData(q);
			},300);
		}        
      }, function() {
      	$(this).removeClass('rsBoxFollower');
		clearTimeout(slideshow);
      });
    
    // Select the first category \ first recent query
    if ($("#cat_col0 > div:first").length > 0)
    {
    	getCatData($("#cat_col0 > div:first").attr('id').substring(4));
    }
    else
    {
    	$("#hover-demo .ellipsis").ellipsis(187);
    	
    	getRSData($(".rsBoxHover a:first").attr('title'));

		// Auto load recent searched new projects amount
		$(function(){
				$("div .rsBox").each(function(){
					$(this).find("span[class=resultsAmount]").load("getResultAmount",
								 { q: $(this).find("a:first").attr("title") },
								 function(data, textStatus) 
								 { 
								 	if (textStatus == "success" && data != "0") {
								 		$(this).parent().html('<a href="' + getSearchURL($(this).parent().parent().find("a:first").attr("title"), extraPreferences + (extraPreferences != "" ? "&" : "") + "new=1") + '" class="newClngAmount">' + data + ' new project' + (data == '1' ? '' : 's') + '</a>');
								 	}
								 	else {
								 		$(this).parent().html('&nbsp;');
								 	}
								 } );
				})
			});
			
		$("a.clrAll").click(function() {
			$.cookie("rs", null);
			$.cookie("conv", null);
			window.location.reload();
		});
    }
		
	$('#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;
	});

	function sendingPage() {
		$('.emailSendingMessage').show();
		$('.emailBody').hide();
	}

	function sendProject() {
		var formArray = ['#nameTxt','#emailTxt'];
		var messageArray = ['Please enter a valid Email address','Please enter a valid Email address']

		if(validateEmails(formArray, messageArray)) {
			sendingPage();
			
			var CallParams = {}; 
			CallParams.type = "POST"; 
			CallParams.url = "sendMail"; 
			CallParams.processData = true; 
			CallParams.data = {type: "0", from: $('#nameTxt').val(), to: $('#emailTxt').val(), comments: $('#commentTxt').val(), cid: globalCid}; 
			CallParams.dataType = "json";
			fGoogleEvent('sendProjectMail','c=' + globalCid); 
			
			CallParams.success = function(data) {
				if (data.status == "ok") {
					$('.emailBoxHead').find('h3').html('Email sent successfully');
					$('.emailSentMessage').find('span').eq(0).html($('#emailTxt').val());
					$('.emailSentMessage').show();
					$('.emailSendingMessage').hide();
				}
				else {
					alert("Error occured while trying to send the mail. please try again");
				}
			};
			 
			CallParams.error = function() {
				alert("Error occured while trying to send the mail. please try again");
			};
			 
			$.ajax(CallParams); 				
		}
	}
});

function validateEmailString(email) {
	var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+[a-zA-Z0-9]{2,4}$/;
	return email != "" && email.match(emailRegEx);
}

function validateEmails(formArray, messageArray){
	var isValid = true;
	
	for(var i=0; i<formArray.length; i++){
		str = $(formArray[i]).val();
		if(validateEmailString(str)){		
			$("#emailBox").find('em').eq(i).html('&nbsp;');	
		}else{
			$("#emailBox").find('em').eq(i).html(messageArray[i]);	
			isValid = false;
		}
	}
	
	return isValid;
}

function setLoadingIcon(text) {
	$("#s4").html('<div><div class="rightboxtop"><div class="rightboxtopL left"></div></div><div class="rightboxcontent" style="height: 142px; padding: 65px 10px 0px 15px; text-align: center;"><img src="images/loader.gif" /><br/><span class="loading">Loading' + (text == '' ? '' : ' ' + text) + ' ...</span><div class="clear"></div></div></div>');
	$('#pager').html('<li>&nbsp;</li>');
}
