

window.onload = initSkillIndex;
var providerTabView;
var jobTabView;

function initSkillIndex() {
	if( $('skillPage') &&
	    $('skillPage').value == 'Y' ) {
		providerTabView = new YAHOO.widget.TabView('provider_tabs');
		removeClassName($('provider_tabs'), 'displayNone');
		
		jobTabView = new YAHOO.widget.TabView('job_tabs');
		removeClassName($('job_tabs'), 'displayNone');
	}

	if( $('totalEarnings') ){
		rollingCounter.init( 
			$('totalEarnings').value, $('totalEarningsStep').value, $('totalEarningsTime').value 
		);
	}

	//create our Accordion instance
	var myAccordion = new Accordion($('accordion'), 'div.boxHeader', 'div.boxContent', {
		opacity: false,
		start:'first-open',
		alwaysHide:true,
		onActive: function(toggler, element){
			var parent = toggler.getParent('div');
			parent.removeClass('closedBox');
		},
		onBackground: function(toggler, element){
			var parent = toggler.getParent('div');
			parent.addClass('closedBox');
		}
	});
	var toggler = new Element('div.boxHeader', {
		
	});
	
		
}

function switchLeftNavBox(box) {
	if( $(box + 'Box').className.search('closedBox') == -1 ){
		$(box + 'Box').addClass('closedBox');
	} else {
		$(box + 'Box').removeClass('closedBox');
	}
} 

function switchCat(catid) {
	var catEntry = document.getElementsByTagName('div');
	for(var i = 0; i < catEntry.length; i++) {
		if( catEntry[i].id.substr(0,5) != 'catid' ){ continue; }
		addClassName(catEntry[i], 'displayNone');
	}
	$('catid'+catid).removeClass('displayNone');

	var catBullets = document.getElementsByTagName('li');
	for(var i = 0; i < catBullets.length; i++) {
		if( catBullets[i].id.substr(0,9) != 'catBullet' ){ continue; }
		removeClassName(catBullets[i], 'on'); // Skills Index
		removeClassName(catBullets[i], 'selected'); // Homepage
	}
	$('catBullet'+catid).addClass('on'); // Skills Index
	$('catBullet'+catid).addClass('selected'); // Homepage
}


/*** ROLLING COUNTER ***/
var rollingCounter = {
	num : '1',
	dH : 35, // Height of one digit
	tickStep : 1,    // how much to tick each interval
	tickTime : 1000, // length of tick interval
	flipStep : 5,  // How much to move each flip interval [must be divisor of height!]
	flipTime : 30, // length of flip interval
	intervals    : new Array(20),
	flipProgress : new Array(20),

	// Initialize counter	
	init : function( newNum, step, time ){	
		newNum = parseInt( newNum );
		if( newNum == 'NaN' ){ return; }

		// Read the dH from rolling counter's clientHeight
		rollingCounter.dH = $('rollingCounterNoScript').clientHeight;

		// Put the number on the page
		$('rollingCounterNoScript').style.display = 'none';
		rollingCounter.num = '' + newNum;
		for( i = 1; i <= rollingCounter.num.length; i++ ){
			rollingCounter.addDigit(i);
		}	
		rollingCounter.putNum();

		// check inc amt and inc time variables
		step = parseInt( step );
		if( step == 'NaN' ){ return; }
		rollingCounter.tickStep = step;

		time = parseInt( time );
		if( time == 'NaN' ){ return; }
		rollingCounter.tickTime = time * 1000;

		// If we are good and positive, start the ticking		
		if( rollingCounter.tickStep > 0 ){		
			setInterval( rollingCounter.tick, rollingCounter.tickTime );
		}
	},

	// Add one digit window
	addDigit : function( i ){
		// Every 3rd digit from 1 (4, 7, 10,...) needs a comma
		if( i > 3 && i % 3 == 1 ){
			var comma       = document.createElement('div');
			comma.className = 'digitComma';
			comma.innerHTML = ',';
			$('counter').insertBefore(comma, $('counterFirst').nextSibling );
  	}

		// Add the digit window
		var elem = $('init_digitWindow').clone();
		elem.id = 'digitWindow' + i;
		elem.style.display = '';
		elem.firstChild.id = 'digitSlider' + i;
	
		$('counter').insertBefore(elem, $('counterFirst').nextSibling );
	},


	/** Puts the number into the space **/
	putNum: function(){
		for( i = 1; i <= rollingCounter.num.length; i++ ){
			var thisDigit = rollingCounter.num.substr( rollingCounter.num.length - i, 1);
			rollingCounter.putDigit(i, thisDigit);
		}
	},

	// Puts one digit into place
	putDigit : function( i, val ){
		// Complex! 
		// dH * 10 is for the extra digits [think of them as 10->19, ex:for flip from 9 -> 14]
		// 9 - val because they are arranged from bottom to top.
		$('digitSlider' + i).style.bottom = 
			((rollingCounter.dH * 10) + ((9 - val) * rollingCounter.dH)) + 'px';
	},

	/** For fliping a single digit **/
	flipDigit : function(i, thisDigit, delta ){
		clearInterval( rollingCounter.intervals[i] ); // sanity
		rollingCounter.flipProgress[i] = 0;           // sanity
		rollingCounter.intervals[i] = setInterval( 
			'rollingCounter.flipper('+i+','+ thisDigit + ',' + delta +');', 
			rollingCounter.flipTime
		);
	},

	// This function is called on interval to slowly move the new digit into place
	flipper : function( i, thisDigit, delta ){
		// Exit condition: when we moved delta digits
		if( rollingCounter.flipProgress[i] >= delta * rollingCounter.dH ){
			clearInterval( rollingCounter.intervals[i] );
			return;
		}
		rollingCounter.flipProgress[i] += rollingCounter.flipStep * delta; // Rate of flipping
		// Move the digit slider down some
		$('digitSlider' + i).style.bottom = 
			((rollingCounter.dH * 10) + ((9 - thisDigit) * rollingCounter.dH) - rollingCounter.flipProgress[i]) + 'px';
	},


	/** increments the number and flips digits **/
	tick : function(){
		rollingCounter.putNum(rollingCounter.num);
		newNum = (parseInt(rollingCounter.num) + rollingCounter.tickStep) + '';

		// If the new number is longer than the old one, we need to add digit(s)
		if( newNum.length > rollingCounter.num.length ) {
	  	for( i = rollingCounter.num.length + 1; i <= newNum.length; i++ ){
				rollingCounter.addDigit(i);
				// pad the number so the digits line up correctly
				rollingCounter.num = '0' + rollingCounter.num; 
			}
		}

		// Foreach digit, calculate the delta, then flip
		for( i = 1; i <= rollingCounter.num.length; i++ ){
			var thisDigit1 = rollingCounter.num.substr( rollingCounter.num.length - i, 1);
			var thisDigit2 = newNum.substr( newNum.length - i, 1);
			if( thisDigit1 != thisDigit2 ){
				var delta = thisDigit2 - thisDigit1;
				if( delta < 0 ){ delta += 10; }       // No negative delta please!
				rollingCounter.flipDigit(i, thisDigit1, delta );
			}
		}

		rollingCounter.num = newNum; // set the new number
	}
} // End rolling counter


//
// Load the customer quotes animated GIF 
//
// type is either 'buyer' or 'provider'
function loadQuote( type ) {
  var randGif = Math.random();
	var animated = '<a href="/p/testimonials"><img src="/media/images/4.0/landing/customer_testimonials_v1_reduced.gif" border="0"/></a>';

	if( type == 'provider' ) {
	  randGif = Math.floor(randGif * 3) + 1;
	  animated = '<a href="/p/provider_testimonials.html"><img src="/media/images/4.0/landing/provider_testimonials_v' + randGif + '.gif" border="0"/></a>';
	}
  else {
		randGif = Math.floor(randGif * 4) + 1;
		animated = '<a href="/p/testimonials"><img src="/media/images/4.0/landing/customer_testimonials_v' + randGif + '_reduced.gif" border="0"/></a>';
	}
  $("landingcustomersays").innerHTML = animated;
}

//
// Load the video
//
function loadVideo( swfUrl ) {
	if( $('mainvideo') ) {
	  var vid = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="541" height="248"><param name="movie" value="' + swfUrl + '" /><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="base" value="' + swfUrl + '"><embed src="' + swfUrl + '" base="' + swfUrl + '" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="541" height="248" wmode="transparent"></embed></object>';
	  $('mainvideo').innerHTML = vid;
	}
}

//
// Check Flash plugin installed or not
//
function isFlashPluginInstalled(){
	try{
		if(typeof navigator.plugins != "undefined"){
			var a = null;
			try{
				a = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			}catch(e1){
			}
			if(typeof navigator.plugins["Shockwave Flash"] == "object" || typeof navigator.mimeTypes["application/x-shockwave-flash"] != "undefined"
				|| typeof navigator.plugins["Shockwave Flash 2.0"] != "undefined" || a){
				return true;
			}else{
				return false;
			}
		}	
	}catch(e){
		
	}
	return false;
}


function LandscapeJS(){
	var landscapeObj = this;

	var keywordsInit = 'Enter search keywords';
	var matchKeywords;
	
	this.init = function(){
		if( document.inpagesearch ) {
			matchKeywords = document.inpagesearch.matchKeywords;
	
			if( matchKeywords.value == '' || matchKeywords.value == keywordsInit ){
				matchKeywords.value = keywordsInit;
				addClassName(matchKeywords, 'keywordslight');
				matchKeywords.setAttribute('touched', 0);
				smartAddEvent(matchKeywords, 'focus', this.setInFocus);
			} else {
				matchKeywords.setAttribute('touched', 1);
			}
		}
	}

	this.setInFocus = function(evt, elem){
		if( elem.getAttribute("touched") != 1 ){
			elem.setAttribute("touched", 1);
			if( elem.name == 'matchKeywords' ){
				elem.value = '';
				removeClassName(elem, 'keywordslight');
			}
		}
	}

	/** Do search generic from a form **/
	this.searchformsubmit = function(form) {
		// Get the value of matchType [complicated because it may be a radio]
		var matchType;
		for (var i = 0; i < form.elements.length; i++) {
			var formItem = form.elements[i];
			if( formItem.name != "matchType" ){ continue; } // not the droids we are looking for

			// if its radio, only counts if its checked.
			if( formItem.type == "radio" ){ 
				if( formItem.checked == true ){ matchType = formItem.value; break }
			} else {
				// Its a hidden or some other thing; just take its value
				matchType = formItem.value;
				break;
			} 
		}
		var url = '/php/search/main/eolsearch.php?matchType=' + matchType + '#page=1';
	
		if( form.matchKeywords && form.matchKeywords.value && form.matchKeywords.value != keywordsInit ){ 
			url += '&matchKeywords=' + form.matchKeywords.value;
		}
		if( form.catFilter && form.catFilter.value ){ 
			url += '&catFilter=' + form.catFilter.value; 
		}
	
		window.location.href = url;
	}

	/** Wrapper to the above that sets the timeout [can't do "window.location.href = X" in an onsubmit] **/
	this.searchformsubmitHandler = function(form){
		setTimeout( function(){ landscapeObj.searchformsubmit(form)}, 1); 
		return false;
	}
};

var landscapeObj = new LandscapeJS();
window.addEvent('load', function(){ landscapeObj.init(); } ); 

function advanceTrain (response) {
	if (response.status == 'success') {
        window.location.href = response.data.returnUrl;
   	}
}

function handleSuccess( obj) {
    var response = eval('(' + obj + ')');
	if( response.status == 'success' ) {
    	advanceTrain(response);
  	} else if ( response.status == 'error' ) {
     	displayErrors( response );
  	}
}

function handleError(obj) {
	
}

function handleNoThanksSuccess (obj) {
	var response = eval('(' + obj + ')');	
	if( response.status == 'success' ) {
		if($('AmexWorkroomReminder')) {
			$('AmexWorkroomReminder').addClass('displayNone');
		} else{
			advanceTrain(response);
		}
	} else if ( response.status == 'error' ) {
        displayErrors( response );
        }	
}

function handleLogoOptSuccess(obj) {
	var response = eval('(' + obj + ')');
	if( response.status == 'success' ) {
		window.location.reload();
	}
}

function displayErrors( response) {
    $(response.errorMsgsEl).removeClass( 'displayNone' );
    $( response.errorMsgsEl + 'List' ).innerHTML = '';
    if (response.errorMsgs) {
        for( var i = 0; i < response.errorMsgs.length; i++ ) {
        	$( response.errorMsgsEl + 'List' ).innerHTML += response.errorMsgs[i];
        }
    }
    if( response.errorIds ) {
        for( var j = 0; j < response.errorIds.length; j++ ) {
            if( $(response.errorIds[j]).getAttribute("type") == 'error' ) {
                $(response.errorIds[j]).addClass( 'highlightError' );
            }
        }
    }
    window.scroll(0,0);
}

//Ajax call to update the note of a watched item
function handleAcceptance(AmexOpenAction) {
	$('csphone').value = $('csphone1').value + $('csphone2').value + $('csphone3').value;
	$code = $('amexcode').toQueryString();
	$code += '&action=agree';
	if (!AmexOpenAction) {
		AmexOpenAction = 'myelance';
	}
	$code += '&AmexOpenAction='+AmexOpenAction;
	
	var options = {
        method: 'post',       
        postBody: $code,
        onSuccess: function(res) { 	$('AmexInterstitialError').addClass('displayNone');
        							handleSuccess(res); },
        onFailure: flowHandleError
    }
    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();	
}

function handleToggleLogo() {
	var answer = confirm("The American Express OPEN(SM) logo will no longer display on your profile. Are you sure?");
	
	if (answer) {
	    $opt = $('amexlogoopt').toQueryString();
		$opt += '&action=togglelogo';
	    var options = {
	        method: 'post',
	        postBody: $opt,
	        onSuccess: function(res) { handleLogoOptSuccess(res); },
	        onFailure: handleError
	    }
	    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
	    request.request();
	} else {
		$('amexlogoopted').checked = true;
	}
}

function handleNoThanks(AmexOpenAction) {
	$code='action=opt_out';
	$code += '&AmexOpenAction='+AmexOpenAction;
	
    var options = {
        method: 'post',
        postBody: $code,
        onSuccess: function(res) { handleNoThanksSuccess(res);},
        onFailure: handleError
    }
    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();
}

function handleAmexSignIn(context) {
    amexCookie = getAmexCookie();
	if (amexCookie == 15601 || amexCookie == 15606 || amexCookie ==15608) {
		window.location='/php/partner/main/AmexInterstitial.php?AmexOpenAction='+context;
	} else {
		window.location='/myelance';
	}
}

function handleSkipNow() {
    $code='action=noaction';
    var options = {
        method: 'post',
        postBody: $code,
        onSuccess: function(res) { flowHandleSuccess(res, 1);},
        onFailure: handleError
    }
    var request = new Ajax('/php/partner/main/AmexInterstitialAHR.php', options);
    request.request();
}


function enableBtn( buttonEnabled, buttonDisabled ) {
	if( buttonEnabled ) {
    	buttonEnabled.removeClass( 'displayNone' );
   	}
    if( buttonDisabled ) {
    	buttonDisabled.addClass( 'displayNone' );
    }
}

function setAmexVisitorCookie() {
	var hasAmexCookie = getAmexCookie() != null;
	if( !hasAmexCookie || getAmexCookie()== 15603) {
		var ridval = getGetParam( "rid" );
		if ( ridval != "" && ridval.length <= 6 ) {
			//-- Visitor with rids are from AMEX invitation: set 1 day cookie
			setCookie( "partner", "15606", "45", "/", ".elance.com", false );
		} else {
			//-- Visitor without rids are from Elance site: set 1 hour cookie
			document.cookie = "partner=15606;path=/;domain=.elance.com;";
		}
	}
}


function setAmexRSVPCookie() {
	var rsvp = getGetParam("amexrsvp");
	if( rsvp != "" && rsvp.length <=10 ) {
		setCookie( "amexrsvp", rsvp, "0.5", "/", ".elance.com", false );
	}
}


function getAmexCookie() {
	return getCookie('partner');
}

function getPartnerCookie() {
        return getCookie('partner2');
}

function handlePartnerOnReg(){
	$('bizTypeRadio').checked = true; 
	handleTypeChange('biz') ;
	$('bizSmall').checked = true; 
	$('category6').checked = true; 
	$('usermanagement').checked = false;
	handleMembershipChange(); 
	var promocode = getCookie('promocode');
	if(promocode) {
		$('promoCode').value = promocode;
		submitPromo();
	}
		
}

function landingRedirect() {
	var url = document.URL;
	var elance = /elance\.com\/$/;

	var olsbPartner = getPartnerCookie();
	var isOlsbPartner = (olsbPartner == 15622 || olsbPartner == 15623);

	if(url.match('/p/landing/') && url.indexOf('provider')>0 && !url.match('olsb') && isOlsbPartner) {
		window.location.href = '/officeliveprovider';
		return;
	}
	if(isOlsbPartner && (url.match(elance)  || url.match('/p/landing/') && url.indexOf('buyer')>0 && !url.match('olsb'))) {
		if(olsbPartner == 15622) {
                	window.location.href = '/officelivebuyerpromo';
			return;
                } else if(olsbPartner == 15623){
			window.location.href = '/officelivebuyer';
		}
		return;
        }
	if(url.match('olsb')) return;

	amexCookie = getAmexCookie();
	if ((url.match(elance) || url.match('/p/landing/') && !url.match('open')) && 
		(amexCookie == 15601 || amexCookie == 15606 || amexCookie ==15608)) {
		var open = '';
		if (url.indexOf('provider')>0) {
			open = 'openlogo/';
		} else {
			open = 'open/';
		}
		if(url.match(elance)) {
			window.location.href = 'open';
		} else {
			window.location.href = url.substring(0,url.indexOf('/p/landing/')+11) + open + url.substring(url.indexOf('/p/landing/')+11, url.length);
		}
	}
}

function hideBannerPopup( userType ) {
  	$('amex'+userType+'MoreInfoBox').addClass('visibilityHidden');
	$('amex' + userType + 'MoreInfoClosed').removeClass('visibilityHidden');
}

function showBannerPopup( userType ) {
  	$('amex'+userType+'MoreInfoBox').removeClass('visibilityHidden');
	$('amex' + userType + 'MoreInfoClosed').addClass('visibilityHidden');
}

function noThanksPartner( divid ) {
	var options = {
                method: 'post',
                onSuccess: function(res) { $( divid ).addClass('displayNone') },
                onFailure: handleError
        }
        var request = new Ajax('/php/partner/main/PartnerInterstitialAHR.php?action=nothanks&type='+divid, options);
        request.request();	
}

function clearGroup ( groupid ) {
	var options = {
		method: 'post',
                onSuccess: function(res) { 
					if($('recommended_count')) {
						if($( 'recommended_count' ).value == 0 ) {
							$('recommended_list').addClass('displayNone');
						} else {
							$( 'recommended_count' ).value = $( 'recommended_count' ).value - 1;
						}
					}
					if($( 'group' + groupid )) $( 'group' + groupid ).addClass('displayNone'); 
					},
                onFailure: handleError
        }
	curAsyncReq = new Ajax('/php/groups/main/groupAHR.php?action=ClearGroup&groupId='+groupid+'&t=' + getDateTime(), options);
	curAsyncReq.request();
}
