// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG TIPS MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Finds all tips based on a specified class name and creates prototips
function PDTips() {this.initialize();}

PDTips.prototype.initialize = function(){
	$$('.tip-dynamic').each(function(tip){
		var me = this;
		var tipId = tip.identify();
		var tipContentId = tipId.split('_')[1];
		var tipTitle = tip.readAttribute('title');
		var tipTrackPath = tip.readAttribute('path');
		
		new Tip(tipId, {
			title : tipTitle,
			ajax: {url: '/ajax.aspx?x=8XHrl0xJZEU%3d',options: {parameters:{id:tipContentId},onComplete: function(transport) {
				if(typeof pageTracker != 'undefined'){
					pageTracker._trackPageview(tipTrackPath);
				}
			}}},
			showOn: 'click',
			hideOn: { element: 'closeButton', event: 'click' },
			width: 400,
			stem: 'topLeft',
			style: 'protoblue',
			offset: { x: 6, y: 3 }
		});
	});
}


// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG ACCORDIONS MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Finds all accordions by class and attaches appropriate behaviors
function PDAccordions (){this.initialize();}

PDAccordions.prototype.initialize = function(){
	var me = this;
	$$('.rail-collapsenav').each(function(div){
		div.select('ul')[0].childElements().each(function(li){
			li.down().observe('click', me.onItemClick.bindAsEventListener(me));			
			li.select('ul')[0].select('li')[li.select('ul')[0].select('li').length-1].setStyle({borderBottom:'none'});
		});
	});	
}

PDAccordions.prototype.onItemClick = function(event){
	event.stop();
	var header = Event.element(event).up();
	var childUl = header.select('ul')[0];	
	if(header.hasClassName('shown')){childUl.hide();header.removeClassName('shown');}else{childUl.show();header.addClassName('shown');}
}

// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG MOBILE CONTENT MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Contains all functions and methods needed within handling ringtones
// - and other mobile content related sections
function PDMobileContent() {this.initialize();}

PDMobileContent.prototype.initialize = function(){
	var me=this; //set reference to current class to pass within constructor	
	$$('.mobilecontent-getit').each(function(link){link.observe('click', me.onGetItClick.bindAsEventListener(me));});
}

PDMobileContent.prototype.onGetItClick = function(event) {
	event.stop() //prevent click behavior
	var element = Event.element(event);
	var link = element.readAttribute('href');
	var artist = (element.readAttribute('artistid') == '') ? '0' : element.readAttribute('artistid');
	var content = element.readAttribute('contentid');
	var postData = {artistid:artist,contentid:content};
	
	//ensure we have google analytics loaded properly before we track this outgoing click
	if(typeof pageTracker != 'undefined'){pageTracker._trackPageview('/outgoing/wlc/thumbplay');}	
	
	//onfailure is left out on purpose
	var options = {parameters:postData, method:'post', onComplete: function(response){}}	
	new Ajax.Request('/ajax.aspx?x=2Gdk0TeHS%2fc%3d', options);	
	
	//open the requested link in a new window
	window.open(link);
}

// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG VOTING MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Looks for all voters (div.voter) and builds the voting elements within it
// - as well as attaches the appropriate event handlers for voting and saving
function PDVoting() {this.initialize();}

PDVoting.prototype.initialize = function(){
	var me=this; //set reference to current class to pass within constructor
	
	//find all voters
	$$('div.voter').each(function(voter){
		var voterId = voter.identify().split('_')[1];
		var votewrapper = new Element('div', {id:'vote_' + voterId});
		var imgUpDown = new Element('img',{src:'/img/icons/thumbupdown.gif'});
		var voteUp = new Element('a',{href:'#',id:'vote_yes_' + voterId}).update('helpful');
		var voteDown = new Element('a',{href:'#',id:'vote_no_' + voterId}).update('not helpful');
		var spanStart = new Element('span').update(' Was this review ');
		var spanMid = new Element('span').update(' or ');
		var spanEnd = new Element('span').update(' for you?');
		var votemessage = new Element('div',{id:'vote_done_' + voterId}).setStyle({display:'none'}).update('Thanks for your vote!');
		
		//attach event observers to handle the clicks
		voteUp.observe('click',me.saveVote.bindAsEventListener(me));
		voteDown.observe('click',me.saveVote.bindAsEventListener(me));
		
		//build the voter html elements
		votewrapper.appendChild(imgUpDown);
		votewrapper.appendChild(spanStart);
		votewrapper.appendChild(voteUp);
		votewrapper.appendChild(spanMid);
		votewrapper.appendChild(voteDown);
		votewrapper.appendChild(spanEnd);
		voter.appendChild(votewrapper);
		voter.appendChild(votemessage);
	});
}

PDVoting.prototype.saveVote = function(event){
	event.stop(); //prevent click behavior
	var element = Event.element(event);
	var yesno = element.identify().split('_')[1];
	var review = element.identify().split('_')[2];
	var postData = {reviewid:review,vote:yesno};
	
	//onfailure is left out on purpose
	var options = {parameters:postData, method:'post', onComplete: function(response){$('vote_' + review).hide(); $('vote_done_' + review).show();}}	
	new Ajax.Request('/ajax.aspx?x=%2f7U%2fTAv2H2I%3d', options);
}


// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG RATING MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Looks for all raters (div.rater) and creates a new rater class to attach
// - which will take care of the rest
function PDRatings() {this.initialize();}

PDRatings.prototype.initialize = function(){
	var me=this; //set reference to current class to pass within Starbox constructor

	//find all raters and create a new starbox for each
	$$('div.rater').each(function(rater){
		new Starbox(rater.identify(),
			rater.readAttribute('currentRating'), {
			rerate: false,
			ghosting: true,
			indicator: '#{average} rating from #{total} votes',
			total: rater.readAttribute('totalRatings'),
			onRate: me.saveRating
		});	
	});
}

PDRatings.prototype.saveRating = function(element, info){
	var indicator = element.down('.indicator');
	var postid = info.identity.split('_')[1];
	var rated = info.rated.toFixed(0);
	var postData = {contentid:postid,rating:rated};
	
	//onfailure is left out on purpose
	var options = {
		parameters:postData,
		method:'post',
		onComplete: function(response){
			var success = (response.responseText == '0') ? false : true;
			if(success){
				indicator.update('You rated ' + rated);
				window.setTimeout(function() {indicator.update('Thanks for voting') }, 2000);
			}else{
				indicator.update('You already rated this post');
			}
		}
	}
	
	new Ajax.Request('/ajax.aspx?x=GUyaekesMlg%3d', options);
}

// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG TABS MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Very simple tabs class that looks for all divs with the classname "tabs"
// - and then attaches event listeners to the tab links that will show/hide
// - the related tabs slides in the div contained within the tab wrapper
function PDTabs() {this.initialize();}

PDTabs.prototype.initialize = function(){
	var index=0;
	var me=this;
	
	//find all div tags that have the tabs classname
	$$('div.tabs').each(function(tabwrapper){
		index=0; //reset the index
		
		if(tabwrapper.select('a.tab').length>0){
			tabwrapper.select('a.tab')[0].addClassName('selected');
			tabwrapper.select('div.tabs-slide')[0].style.display='block';
			
			tabwrapper.select('a.tab').each(function(tablink){
				tablink.observe('click',me.onTabClick.bindAsEventListener(me,tabwrapper.identify(),index));
				index++;
			});
		}
	});
}

PDTabs.prototype.onTabClick = function(event,tabid,index){
	event.stop(); //prevent link behavior
	var tabs=$(tabid);
	var tablinks=tabs.select('a.tab');
	var tabslides=tabs.select('div.tabs-slide');
	var tabclicked=tablinks[index];
	var tabslideclicked=tabslides[index];
	
	tabslides.each(function(slide){slide.hide();}); //hide each slide
	tablinks.each(function(tab){tab.removeClassName('selected');}); //remove selected from all tab links
	tabclicked.addClassName('selected'); //make clicked tab selected
	tabslideclicked.show(); //show corresponding slide
}

// - ///////////////////////////////////////////////////////////////////////
// - PHONEDOG COMMENTS MODULE
// - ///////////////////////////////////////////////////////////////////////
// - Looks for a submit button with the comment id and then attaches
// - event click observer to sumbit the comment via ajax
function PDComments() {this.initialize();}

PDComments.prototype.initialize = function(){	
	// Ensure that we have a comment submit button since the class
	// gets initialized on all pages but not all pages have comment forms
	if($('cmt_submit')){
		var me = this;
		
		// find all comments-vote divs and build the voting icons
		$$('.comments-vote').each(function(div){
			var voteResponse = new Element('span');
			var votePlus = new Element('a', {href:'#', 'class':'comments_vote_plus', title:'I like... I like!'});
			var voteMinus = new Element('a', {href:'#', 'class':'comments_vote_minus', title:'This one... ah, not so much!'});
			var voteReport = new Element('a', {href:'#', 'class':'comments_vote_report', title:'Ouch... I\'m gonna tell the PhoneDog!'});

			votePlus.observe('click',me.onVoteClick.bindAsEventListener(me,2));
			voteMinus.observe('click',me.onVoteClick.bindAsEventListener(me,1));
			voteReport.observe('click',me.onVoteClick.bindAsEventListener(me,-1));
			
			div.appendChild(voteResponse);
			div.appendChild(votePlus);
			div.appendChild(voteMinus);
			div.appendChild(voteReport);
		});

		// build the user login / registration information 
		// if we have a user that is currently not logged in		
		if(!pdUser_IsLoggedIn){		
			var userWrapper = $('commentform-user');
			userWrapper.update();
			
			var userNewWrapper = new Element('div', {'class':'commentform-userinfo clearfix', id:'commentform-userinfo-new'});			
			var userNewInfoTxt = new Element('div', {'class':'commentform-userinfotxt'}).update('First time posting? A confirmation e-mail will be sent to you after submitting.');

			var userNewInfo1 = new Element('div', {'class':'commentform-userinfo1'});
			userNewInfo1.appendChild(new Element('b').update('Display name:'));
			userNewInfo1.appendChild(new Element('input', {type:'text', id:'user_new_name', maxlength:20}));
			
			var userNewInfo2 = new Element('div', {'class':'commentform-userinfo2'});
			userNewInfo2.appendChild(new Element('b').update('Email:'));
			userNewInfo2.appendChild(new Element('input', {type:'text', id:'user_new_email', maxlength:80}));
			
			var userNewInfoToggle = new Element('div', {'class':'commentform-userinfo-toggle'});
			userNewInfoToggle.appendChild(new Element('span').update('Posted before or have a PhoneDog account? '));
			userNewInfoToggle.appendChild(new Element('a', {id:'commentform-userinfo-linknew', style:'font-weight:bold;'}).update('Sign in here')).observe('click',this.onSigninClick.bindAsEventListener(this));			
			userNewWrapper.appendChild(userNewInfoTxt);
			userNewWrapper.appendChild(userNewInfo1);
			userNewWrapper.appendChild(userNewInfo2);
			userNewWrapper.appendChild(userNewInfoToggle);			

			var userExistingWrapper = new Element('div', {'class':'commentform-userinfo clearfix', id:'commentform-userinfo-existing', style:'display:none;' });
			var userExistingInfoTxt = new Element('div', {'class':'commentform-userinfotxt'}).update('Returning members, please enter your username and password.');

			var userExistingInfo1 = new Element('div', {'class':'commentform-userinfo1'});
			userExistingInfo1.appendChild(new Element('b').update('Username:'));
			userExistingInfo1.appendChild(new Element('input', {type:'text', id:'user_existing_username', maxlength:20}));
			
			var userExistingInfo2 = new Element('div', {'class':'commentform-userinfo2'});
			userExistingInfo2.appendChild(new Element('b').update('Password:'));
			userExistingInfo2.appendChild(new Element('input', {type:'password', id:'user_existing_password', maxlength:20}));			
			
			var userExistingInfoToggle = new Element('div', {'class':'commentform-userinfo-toggle'});
			userExistingInfoToggle.appendChild(new Element('span').update('Posted before or have a PhoneDog account? '));
			userExistingInfoToggle.appendChild(new Element('a', {id:'commentform-userinfo-linkexisting', style:'font-weight:bold;'}).update('First-time poster')).observe('click',this.onSigninClick.bindAsEventListener(this));
			userExistingInfoToggle.appendChild(new Element('span').update(', &nbsp; or '));
			userExistingInfoToggle.appendChild(new Element('a', {id:'commentform-userinf-forgot', href:'/community/login.aspx'}).update('forgot your login?'));												
			userExistingWrapper.appendChild(userExistingInfoTxt);
			userExistingWrapper.appendChild(userExistingInfo1);
			userExistingWrapper.appendChild(userExistingInfo2);
			userExistingWrapper.appendChild(userExistingInfoToggle);
			
			userWrapper.appendChild(userNewWrapper);
			userWrapper.appendChild(userExistingWrapper);
			
			// add extra footer information
			var footerInfo = $('commentform-footer-user');
			var footerInfoWrapper = new Element('div', {'class':'commentform-footer'}).update('<b>Email addresses are never displayed, but are required to confirm your comments.</b> Please keep your comments relevant to this post. <span>When you enter your name and email address, we\'ll send you a link to confirm your comment, and a password. To leave subsequent comments, simply use that password.</span>');
			footerInfo.appendChild(footerInfoWrapper);
		}
		
		// Attach event listeners to reply links
		$$('.comments-reply').each(function(reply){reply.observe('click',me.onReplyClick.bindAsEventListener(me));});		
	
		// attach input field beautifications
		$('commentform').select('input, textarea').each(function(input){
			input.observe('focus',me.onInputFocus.bindAsEventListener(me));
			input.observe('blur',me.onInputBlur.bindAsEventListener(me));
		});
		
		// reset the submit button
		$('cmt_submit').value='Submit comment';
		$('cmt_submit').disabled=false;
		$('cmt_submit').observe('click',this.onSubmitClick.bindAsEventListener(this));				
		
		// reset possibly cached values
		$('cmt_parentid').value = '0';
		$('cmt_txt').value = '';
		
		// if we have a comment_ hash in the location then scroll 
		// the window down to that element
		if(window.location.hash && window.location.hash.indexOf('comment_')!=-1){
			if($(window.location.hash.replace('#',''))){
				$(window.location.hash.replace('#','')).scrollTo();
			}
		}
	}
}

PDComments.prototype.isEmail = function(s){
	var good="@_-.:/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	var upper=s.toUpperCase()
	var valid=true;	
	for(x=0; x>s.length; x++){c=upper.charAt(x);for(y=0; y<good.length; y++){if(c==good.charAt(y)){break;}}if(y==good.length){valid=false;break;}}	
	if (!valid || s.length < 7 || s.indexOf("@") == "-1" || s.indexOf(".") == "-1" || s.indexOf("@") != s.lastIndexOf("@")) {return (false);}else{return (true);}
}

PDComments.prototype.isValidUsername = function(s){
	var goodCharacters = ['@','_','-','.','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9'];
	var usernameUpper = s.toUpperCase();
	var isValid = true;
	for(var x=0; x<usernameUpper.length; x++){if(goodCharacters.indexOf(usernameUpper.charAt(x)) == -1){isValid = false;}}
	return isValid;
}

PDComments.prototype.getCommentId = function(clickElement){
	var divItem = clickElement.up('.comments-item');
	return divItem.identify().split('_')[1];
}

PDComments.prototype.showError = function(msg){
	$('commentform-errors').update(msg);
}

PDComments.prototype.onSigninClick = function(event){
	var element = Event.element(event);
	var id = element.identify();	

	//reset all fields
	$('user_new_name').value = '';
	$('user_new_email').value = '';
	$('user_existing_username').value = '';
	$('user_existing_password').value = '';	

	if(id == 'commentform-userinfo-linknew'){
		$('commentform-userinfo-new').hide();
		$('commentform-userinfo-existing').show();
	}else{
		$('commentform-userinfo-existing').hide();	
		$('commentform-userinfo-new').show();		
	}
}

PDComments.prototype.onInputFocus = function(event){
	var element = Event.element(event);
	element.addClassName('on');
}

PDComments.prototype.onInputBlur = function(event){
	var element = Event.element(event);
	element.removeClassName('on');
}

PDComments.prototype.onVoteClick = function(event, vote){
	event.stop();
	var element = Event.element(event);
	var indicator = element.up().down('span');
	var commentId = this.getCommentId(element);
	var postData = {contentid:commentId, rating:vote};
	var saveVote = true;
	
	// make the user confirm reporting a comment
	if(vote == -1 && !confirm('Are you sure you want to report this comment?')){
		saveVote = false;
	}
	
	if(saveVote){
		var options = {
			parameters:postData,
			method:'post',
			onComplete: function(response){
				// -1 = indicates comment was reported
				// 0 = indicates previously voted
				// otherwise returns new rating of comment
				if(response.responseText == -1){
					indicator.update('Comment reported!');
				}else if(response.responseText == 0){
					indicator.update('You already voted');
				}else{
					if(vote == 1){indicator.update('You voted down');}else{indicator.update('You voted up');}
					window.setTimeout(function() {indicator.update('Thanks for voting') }, 2000);
				}
				
				//hide the voting links
				element.up().select('a').each(function(link){link.hide();});
			}
		}
		new Ajax.Request('/ajax.aspx?x=GUyaekesMlg%3d',options);
	}
}

PDComments.prototype.onReplyClick = function(event){
	event.stop();
	var element = Event.element(event);
	var commentId = this.getCommentId(element);
	var replyinfo = $('commentform-replyinfo');
	var author = element.up('.comments-item').down('.comments-header').childElements()[0].innerHTML;
	var replyTxt = new Element('span').update('You\'re replying to ');
	var replySpace = new Element('span').update(' - ');
	var authorLink = new Element('a',{href:'#comment_'+commentId}).update(author);
	var removeLink = new Element('a',{href:'#'}).update('undo reply');
	removeLink.observe('click',this.onReplyRemoveClick.bindAsEventListener(this));

	// set reply information	
	replyinfo.update();
	replyinfo.appendChild(replyTxt);
	replyinfo.appendChild(authorLink);
	replyinfo.appendChild(replySpace);
	replyinfo.appendChild(removeLink);	
	
	// store the reply comment id
	$('cmt_parentid').value = commentId;
	
	// scroll to the comment form
	$('commentform').scrollTo();
}

PDComments.prototype.onReplyRemoveClick = function(event){
	event.stop();
	$('cmt_parentid').value = '0';
	$('commentform-replyinfo').update();
}

PDComments.prototype.onSubmitClick = function(event){	
	// these are always available
	var submit = Event.element(event);
	var comment = $('cmt_txt');
	var isloggedin = pdUser_IsLoggedIn;
	var isnewuser = (isloggedin || $('commentform-userinfo-new').style.display == 'none')?false:true;	
	var postData;
	var name = '';
	var email = '';
	var username = '';
	var password = '';
	
	// these are only available if we are not logged in
	if(!isloggedin){
		var new_name = $('user_new_name');
		var new_email = $('user_new_email');
		var existing_username = $('user_existing_username');
		var existing_password = $('user_existing_password');
	
		if(isnewuser){
			if(new_name.value==''){this.showError('Please enter your desired display name');new_name.focus();return false;}
			if(new_email.value==''){this.showError('Please enter your email address');new_email.focus();return false;}
			if(new_name.value.length<6){this.showError('Your display name must be a minimum of 6 characters');new_name.focus();return false;}
			if(!this.isValidUsername(new_name.value)){this.showError('Display name contains invalid characters - please use only a combination of letters, numbers, and the characters @._ but no spaces');new_name.focus();return false;}
			if(!this.isEmail(new_email.value)){this.showError('Your email address appears to be invalid - Please double-check it and try again.');new_email.focus();return false;}
		}else{
			if(existing_username.value==''){this.showError('Please enter your username');existing_username.focus();return false;}
			if(existing_password.value==''){this.showError('Please enter your password');existing_password.focus();return false;}		
		}
		
		// set variables
		name = new_name.value;
		email = new_email.value;
		username = existing_username.value;
		password = existing_password.value;		
	}
	
	//validate entering a proper comment	
	if(comment.value==''){this.showError('Please enter your comments');comment.focus();return false;}	
	
	submit.value='Submitting';
	submit.disabled=true;
	
	var postData = {
		cmt_threadid:$('cmt_threadid').value,
		cmt_parentid:$('cmt_parentid').value,
		cmt_itemid:$('cmt_itemid').value,
		cmt_sectionid:$('cmt_sectionid').value,
		cmt_referrerurl:$('cmt_referrerurl').value,
		cmt_txt:$('cmt_txt').value.stripScripts().stripTags().gsub('\n','<br/>'),
		user_new_name:name,
		user_new_email:email,
		user_existing_username:username,
		user_existing_password:password
	};	

	var options = {
		parameters:postData,
		method:'post',
		onSuccess: function(response){
			var resp = response.responseText.evalJSON(true);
			
			// Present user error here based on whether we have a result that's "OK"
			// or a possible error wich would indicate a user registration or signin problem			
			if(resp.result == 'OK'){
				$('commentform-errors').update();
				$('commentform').hide();
				$('commentsubmitted').show();
				$('commentsubmitted').update('<b>Thanks for submitting your comment.</b> If this is your first time posting, please check your email inbox for instructions on how to activate your comment. If you have posted before, then you\'ll just need to refresh this page to view your comment.');	
			}else{
				//show the error message and enable the submit button again
				$('commentform-errors').update(resp.errorMessage);	
				submit.value='Submit Comment';
				submit.disabled=false;						
			}
		},
		onFailure: function(response){
			$('commentform').hide();
			$('commenterror').show();
			$('commenterror').update('<b>Oooops - an error has occurred</b> We\'ve had some difficulty saving your comment and have alerted the appropriate PhoneDog to take a look at this issue. You may also try submitting your comment again in a few minutes.');
		}		
	}
	
	new Ajax.Request('/ajax.aspx?x=AIeKmTTTYnM%3d',options);
}


// Old stuff
function fnValidNumericField(field, fieldSize, fieldDisplayName) {
	if (field.value == "" ) {alert("Please enter " + fieldDisplayName + ".");}
	else if (field.value.length < fieldSize) {alert(fieldDisplayName + " is incomplete.");}
	else if (!fnOnlyDigits(field.value)) {alert(fieldDisplayName + " is incorrect.\nPlease enter only numbers.");}
	else{return (true);}
	field.focus();
	return (false);
}

function fnY2k(number) { return (number < 1000) ? number + 1900 : number;}
function fnValidDate (thisDate,sep) {
	if (thisDate.length == 10) {
		if (thisDate.substring(2,3) == sep && thisDate.substring(5,6) == sep) {
			var month  = thisDate.substring(0,2);
			var date = thisDate.substring(3,5);
			var year  = thisDate.substring(6,10);

			var test = new Date(year,month-1,date);

			if (year == fnY2k(test.getYear()) && (month-1 == test.getMonth()) && (date == test.getDate())) {
				why = '';
				return true;
			}else {
				why = 'the date is invalid';
				return false;
			}
		}else {
			why = 'you can only use slashes \( \/\) between the numbers';
			return false;
		}
	}else {
		why = 'the date is not long enough';
		return false;
	}
}

function fnOnlyDigits(numberStr) {
	var validChars = "0123456789";
	for (var i=0; i<numberStr.length; i++) {
		if (validChars.indexOf(numberStr.charAt(i)) == "-1")
			return (false);
	}
	return (true);
}

function fnValidEmail(tfName) {
	var GoodChars = "@_-.:/ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	var UpperEmail = tfName.value.toUpperCase()
	var ValidChars = true;
	
	for (tfCharNum = 0; tfCharNum > tfName.value.length; tfCharNum++) {
		Char = UpperEmail.charAt(tfCharNum);
		for (gcCharNum = 0;  gcCharNum < GoodChars.length;  gcCharNum++) {
				if (Char == GoodChars.charAt(gcCharNum))
				break;
		}
					
		if (gcCharNum == GoodChars.length)   {
			ValidChars = false;
			break;
   		}
	}
	
	if (!ValidChars || tfName.value.length < 7 || tfName.value.indexOf("@") == "-1" ||
		tfName.value.indexOf(".") == "-1" || tfName.value.indexOf("@") != tfName.value.lastIndexOf("@")) {
			return (false);
	}
	return (true);
}

function fnCertDetails(){	
	var url = 'http://www.phonedog.com/content/redirect.aspx?id=73'	
	thewindow = window.open(url,"certWin", config="height=512,width=500,toolbar=no,menubar=no,scrollbars=no,resizable=yes,location=no,directories=no,status=no");
}

function fnFindPlan(){
	var fm = document.forms['frmStates'];
	var sel = fm.s.selectedIndex;
	
	if(sel == 0){
		alert('Please select your state...');
		fm.s.focus();
		return false;
	}
	else
		return true;
}

function fnFindPlan2(){
	var fm = document.forms['frmStates2'];
	var sel = fm.s.selectedIndex;
	
	if(sel == 0){
		alert('Please select your state...');
		fm.s.focus();
		return false;
	}
	else
		return true;
}

function fnLLDFindPlan(){
	var fm = document.forms['frmLLDStates'];
	var rt = 0;
	
	if(fm.a.value == ""){alert("Please enter your Area Code");fm.a.focus();return false;}
	if(fm.p.value == ""){alert("Please enter your phone number's Prefix");fm.p.focus();return false;}
	if(!fnValidNumericField(fm.a,3,"Your Area Code")){fm.a.focus();return false;}
	if(!fnValidNumericField(fm.p,3,"Your Phone Number's Prefix")){fm.p.focus();return false;}
	if(fm.a.value.length < 3){alert("Your phone number's Area Code is incomplete.");fm.a.focus();return false;}
	if(fm.p.value.length < 3){alert("Your phone number's Prefix is incomplete.");fm.p.focus();return false;}
}

function fnLDPMFindPlan(){
	var fm = document.forms['frmLDPMStates'];
	var rt = 0;
	
	if(fm.a.value == ""){alert("Please enter your Area Code");fm.a.focus();return false;}
	if(fm.p.value == ""){alert("Please enter your phone number's Prefix");fm.p.focus();return false;}
	if(!fnValidNumericField(fm.a,3,"Your Area Code")){fm.a.focus();return false;}
	if(!fnValidNumericField(fm.p,3,"Your Phone Number's Prefix")){fm.p.focus();return false;}
	if(fm.a.value.length < 3){alert("Your phone number's Area Code is incomplete.");fm.a.focus();return false;}
	if(fm.p.value.length < 3){alert("Your phone number's Prefix is incomplete.");fm.p.focus();return false;}
}

function fnVoipFindPlan(){return true;}

function fnOpenPopup(url,theWidth,theHeight){
	var theTop;
	var theLeft;
	
    if (document.all){
		theTop=(screen.height/2)-(theHeight/2);
		theLeft=(screen.width/2)-(theWidth/2)+175;
	}else{
		theTop=100;
		theLeft=5
		00;
	}
	
	var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",toolbar=0,location=0,directories=0,resizable=1,status=0,menubar=0,scrollbars=no";
	theWin=window.open(url,'',features);
}

function fnOpenPopupScrolling(url,theWidth,theHeight){
	var theTop;
	var theLeft;
	
    if (document.all){
		theTop=(screen.height/2)-(theHeight/2);
		theLeft=(screen.width/2)-(theWidth/2)+175;
	}else{
		theTop=100;
		theLeft=5
		00;
	}

	var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",toolbar=0,location=0,directories=0,resizable=1,status=0,menubar=0,scrollbars=yes";
	theWin=window.open(url,'',features);
}

function fnPop(url,theWidth,theHeight,theTop,theLeft,scrollbars){
	if(scrollbars == 1)
		scrollbars = 'yes';
	else
		scrollbars = 'no';
			
	var features='height='+theHeight+',width='+theWidth+',top='+theTop+',left='+theLeft+",toolbar=0,location=0,directories=0,resizable=1,status=0,menubar=0,scrollbars="+scrollbars;
	theWin=window.open(url,'popWin',features);
}

function fnBBB(){
	var features='height=400,width=500,top=0,left=0,toolbar=0,location=1,directories=0,resizable=1,status=0,menubar=0,scrollbars=yes';	
	theWin=window.open('http://www.phonedog.com/content/redirect.aspx?id=72','BBBWin',features);
}


var ccDel = " "

function fnStrp(s, b){var i;var r="";for (i=0;i<s.length;i++){var c = s.charAt(i);if(b.indexOf(c)==-1) r+=c;}return r;}

function fnValidateCC(ct,cn){
	var s = "";
	var fm = document.forms['signupForm'];

	if (ct == "Visa"){s = "Visa";
	}else if (ct == "MasterCard") {s = "Master Card" ;
	}else if (ct == "Amex"){s = "American Express";
	}else if (ct == "Discover"){s = "Discover Card";
	}else{
		alert("Please select a credit card type.");
		fm.CCType.focus();
		return (false);
	}
	
	if(fm.CCNumber.value == ''){
		alert("Please enter your credit card number.");
		fm.CCNumber.focus();
		return (false);
	}
	
	var sn = fnStrp(cn,ccDel);
	
	if (!fnMatchCC(ct,sn)) {
		alert("The Credit Card number you entered is not a valid " + s + " number. Please re-enter it and try again.");
		fm.CCNumber.focus();
		return(false);
	}else {
		if(fm.CCExpMo.selectedIndex == 0 && fm.CCExpYear.selectedIndex == 0) {alert("Please select your credit card expiration date.");fm.CCExpMo.focus();return (false);}
		if(fm.CCExpMo.selectedIndex == 0) {alert("Please select your credit card expiration month.");fm.CCExpMo.focus();return (false);}
		if(fm.CCExpYear.selectedIndex == 0) {alert("Please select your credit card expiration year.");fm.CCExpYear.focus();return (false);}

		if((ct == "Visa" || ct == "Amex" || ct == "MasterCard") && fm.CCBackCode.value == '') {alert("Please enter your " + s + " Security Code.\nFor more information click on the \"What's this\" link.");fm.CCBackCode.focus();return (false);}
		if((ct == "Visa" || ct == "MasterCard") && !fnValidNumericField(fm.CCBackCode, 3, "Your Visa/Master Card Security Code")){fm.CCBackCode.focus();return (false);}
		if(ct == "Amex" && !fnValidNumericField(fm.CCBackCode, 4, "Your American Express Security Code")){fm.CCBackCode.focus();return (false);}
		if((ct == "Visa" || ct == "MasterCard") && fm.CCBackCode.value.length == 4) {alert("Your Visa/Master Card Security Code can only be three numbers.");fm.CCBackCode.focus();return (false);}
		if(fm.CCNameOnCard.value == "") {alert("Please enter the card holders name as it appears on the credit card.");fm.CCNameOnCard.focus();return (false);}
		if(fm.CCZip.value == "") {alert("Please enter the credit card's billing zip code.");fm.CCZip.focus();return (false);}
		return (true);
	}
}

function fnIsCC(st) {
	if(st.length>19)
		return (false);

	sum=0;
	mul=1;
	l=st.length;

	for(i = 0; i < l; i++) {
		digit = st.substring(l-i-1,l-i);
		tproduct = parseInt(digit ,10)*mul;
		
		if (tproduct >= 10)
			sum += (tproduct % 10) + 1;
		else
			sum += tproduct;
			
	if (mul == 1)
		mul++;
	else
		mul--;
	}


	if ((sum % 10) == 0)
		return (true);
	else
		return (false);
}


function fnIsVisa(cc){if(((cc.length==16)||(cc.length==13))&&(cc.substring(0,1)==4))return fnIsCC(cc);return false;}
function fnIsMasterCard(cc){xd = cc.substring(0,1);yd = cc.substring(1,2);if ((cc.length == 16) && (xd == 5)&&((yd >= 1) && (yd <= 5)))return fnIsCC(cc);return false;}
function fnIsAmericanExpress(cc){xd = cc.substring(0,1);yd = cc.substring(1,2);if ((cc.length == 15) && (xd == 3) &&((yd == 4) || (yd == 7))) return fnIsCC(cc);return false;}
function fnIsDiscover(cc){xyd = cc.substring(0,4);if ((cc.length == 16) && (xyd == "6011")) return fnIsCC(cc);return false;}

function fnMatchCC(ct,cn){
	var r = true;
	if((ct=="Visa")&&(!fnIsVisa(cn))) r=false;
	if((ct=="MasterCard")&&(!fnIsMasterCard(cn))) r=false;
	if((ct=="Amex")&&(!fnIsAmericanExpress(cn))) r=false;
	if((ct=="Discover")&&(!fnIsDiscover(cn))) r=false;
	return r;
}


if(typeof Prototype != 'undefined'){
	document.observe('dom:loaded', function() { // once the DOM is loaded  
		//initialize all global classes	
		var pdRatings = new PDRatings();
		var pdTabs = new PDTabs();
		var pdVoting = new PDVoting();
		var pdMobileContent = new PDMobileContent();
		var pdAccordions = new PDAccordions();
		var pdTips = new PDTips();
		var pdComments = new PDComments();
		
		//remove the last border on the right of the news on the homepage
		if($('home-news')){$$('.head-newsitem')[3].setStyle({borderRight:'none'});}
	  
		//initialize footer news carousel if we have it on the page
		//and remove the last border on each of the slides
		if($('footernews-wrapper')){		
			new Carousel($('footernews-scroller'),
				$$('#footernews-scroller .carousel-footernews-slide'),
				$$('#footernews-wrapper a.carousel-jumper','#footernews-wrapper a.carousel-control'),{duration: 1,auto: false}
			);
			
			$$('#footernews-scroller .carousel-footernews-slide').each(function(slide){
				slide.select('div.footnewsitem')[4].setStyle({borderRight:'none'});
			});
		}
		
		//initialize rail featured phones caroulse if we have it on the page
		if($('featphones-wrapper')){
			new Carousel($('featphones-scroller'),
				$$('#featphones-scroller .carousel-featphones-slide'),
				$$('#featphones-wrapper a.carousel-control'),{duration: 1,frequency: 4,	auto: true}
			);	
		}
		
		//initialize phonedogs editors carousel which is only available 
		//on the forums homepage at the moment...
		if($('phonedogs-wrapper')){
			new Carousel($('phonedogs-scroller'),
				$$('#phonedogs-scroller .carousel-phonedogs-slide'),
				$$('#phonedogs-wrapper a.carousel-jumper','#phonedogs-wrapper a.carousel-control'),	{duration: 1,frequency: 5,selectedClassName: 'selected',auto: true}
			);	
		}
		
		//initialize mobile content carousel if available
		if($('ringtones-wrapper')){
			new Carousel($('ringtones-scroller'),
				$$('#ringtones-scroller .carousel-ringtones-slide'),
				$$('#ringtones-wrapper a.carousel-jumper','#ringtones-wrapper a.carousel-control'),	{duration: 1,auto: false}
			);	
		}
		
		//initialize videos carousel if available (on community homepage only at the moment)
		if($('carousel-videos-wrapper')){
			new Carousel($('carousel-videos-scroller'),
				$$('#carousel-videos-scroller .carousel-videos-slide'),
				$$('#carousel-videos-wrapper a.carousel-jumper','#carousel-videos-wrapper a.carousel-control'),	{duration: 1,auto: false}
			);	
		}
	});
}

