 
// on page load
$(function(){

	var msg = $('div.systemMsg');
	if(msg.length){
		var title = $('legend', msg).html();
		var items = '<ul>'+$('ul:first', msg).html()+'</ul>';
		overlay(items, {title: title, content: true});
	}

});



function isEmail(str) {
	var re = new RegExp(/^[\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/);
	return re.test(str);
}

function isRealPhoneNumber(str){
	var prefix = str.substring(0,3);
	if(prefix!='111'&&prefix!='222'&&prefix!='333'&&prefix!='444'&&prefix!='555'&&prefix!='666'&&prefix!='777'&&prefix!='999'){
		var myRegxp = /^([2-9]{1}[0-8]{1}[0-9]{1}[-][2-9]{1}[0-9]{1}[0-9]{1}[-][0-9]{1}[0-9]{1}[0-9]{1}[0-9]{1})$/;
		return myRegxp.test(str);
	}
	else{
		return false;
	}
}

function trim(str){
   return str.replace(/^\s*|\s*$/g,"");
}


function cleanupPhoneNumber(phoneNumber){
	var reg = new RegExp("^(1[ .-]*)?[ (]*([2-9][0-9]{2})[) .-]*([0-9]{3})[ .-]*([0-9]{4})$", "i");
	var m = reg.exec(phoneNumber);
	if (m != null) {
		return m[2]+'-'+m[3]+'-'+m[4];
	}
	return phoneNumber;
}



function encode(str){
	// simple one way encryption (checksum)
	// created: September 30, 2009
	// modified: December 14, 2009
	// author: Jamie Beck <jbeck@terabit.ca>
	
	var l = str.length;
	var i;
	var sum = 0;
	for(i = 0; i < l-1; i++){
		sum = sum + Math.pow(str.charCodeAt(i), i+1);
	}
	return sum;
}

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
	if (document.cookie.length>0){
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1){
		c_start=c_start + c_name.length+1;
		c_end=document.cookie.indexOf(";",c_start);
		if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		}
	  }
	return "";
}

function popup(pageURL, attr){
	// creates popup window
	// created: December 9, 2009
	// author: Jamie Beck <jbeck@terabit.ca>

	var defaultAttr = {
		height:			400,
		width:			450,
		toolbar:		'no',
		menubar:		'yes',
		scrollbars:		'yes',
		resizable:		'yes',
		location:		'yes',
		directories:	'no',
		status:			'yes'
	};
	
	if(typeof attr == 'undefined'){
		// if not attributes were given create empty attr object
		var attr = {};
	}

	// use default attr for any not explicitly given
	for(i in defaultAttr){
		if(typeof attr[i] == 'undefined'){
			attr[i] = defaultAttr[i];
		}
	}

	// turn attributes into usable string
	var attrStr = '';
	for(i in attr){
		attrStr = attrStr + ',' + i + '=' + attr[i];
	}
	
	// launch the window
	thewindow = window.open(pageURL, "_blank", attrStr);
}
function applyPlaceHolder(targetElm){
	 
   jQuery.support.placeholder = false;
   test = document.createElement('input');
   if('placeholder' in test) jQuery.support.placeholder = true;
   
   if(!$.support.placeholder) { 
      $(':text', targetElm).focus(function () {
         if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
            $(this).val('').removeClass('hasPlaceholder');
         }
      }).blur(function () {
         if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
            $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
         }
      }).blur();
      $(':text.hasPlaceholder').closest('form').submit(function () {
         $(':text.hasPlaceholder', this).val('');
      });
	 
	   
	   
   }
}
function overlayMessage(title, content){
	var overlayElm = document.getElementById('overlayContainer');
	if(!overlayElm){
		$('body').append('<div id="overlayContainer" title="" style="display:none;"></div>');
		overlayElm = document.getElementById('overlayContainer');
	}
	
	$(overlayElm).attr('title', title);
	$(overlayElm).html(content);
	$(overlayElm).dialog({width: '500px', modal: true, buttons: {'Ok': function() { $(this).dialog("close"); }}});
	$(overlayElm).dialog('open');
}	
	  
function overlay(pageURL, attr){
	// creates overlay 
	// created: September 14, 2010
	// author: Jamie Beck <jbeck@terabit.ca>

	var defaultAttr = {
		height:			'auto',
		width:			'450px',
		title:			'',
		modal:			true,
		content:		false,
		id:				'overlayContainer'
	};
	
	
	
	if(typeof attr == 'undefined'){
		// if not attributes were given create empty attr object
		var attr = {};
	}

	// use default attr for any not explicitly given
	for(i in defaultAttr){
		if(typeof attr[i] == 'undefined'){
			attr[i] = defaultAttr[i];
		}
	}
	
	var overlayElm = document.getElementById(attr['id']);
	if(!overlayElm){
		$('body').append('<div id="' + attr['id'] + '" title="" style="display:none;"></div>');
		overlayElm = document.getElementById(attr['id']);
	}
	$(overlayElm).attr('title', attr.title);
		
	if(attr['content']){
		// content given so use pageURL as the content
		$(overlayElm).html(pageURL);
		$(overlayElm).dialog(attr).dialog('open');
		$(overlayElm).trigger('loaded');
	}
	else{
		// get content from pageURL
		$.post(pageURL, (attr.post)?attr.post:{}, function(data, textStatus){
			$(overlayElm).html(data);
			$(overlayElm).dialog(attr).dialog('open');
			$(overlayElm).trigger('loaded');
		});
	}
	
	return overlayElm;
}

function displaySystemMsg(systemMsg){
	// modified: 2011-09-23
	if(systemMsg.length > 0){
		alert(systemMsg.join('\n'));
	}
}
function showVoting(element){
	 
	var div_id = $(element).attr('id');
	 


	$('#v_'+div_id).toggle(150, function() {
		// Animation complete.
	});

}


function reviewBump(scoreElm, reviewId, score){
	$.getJSON('/rpc/', {method: 'reviewBump', params: $.param({reviewId: reviewId, score: score})}, function(data){
			if(data.result){
				// it worked
				$(scoreElm).text(data.result['bumpScore']);
				overlay('Your bump has been recorded.', {title: 'Review Bump', content: true});
			}
			else if(data.error){
				// error detected
				if(data.error.code){
					overlay(data.error.message, {title: 'Review Bump', content: true});
				}
				else {
					overlay(data.error, {title: 'Review Bump', content: true});
				}
			}
			else{
				// unknown
			}
		}
	);
	
	return false;
}

function downloadCheck(productId, r){
	$.getJSON('/rpc/', {method: 'downloadCheck', params: $.param({productId: productId})}, function(data){
			if(data.result){
				// it worked
				if(data.result['allowDownload']){
					// already bought so let them download
					window.location = 'd.php?r='+r;
				}
				else{
					// sufficient balance, need to purchase
					overlay('You have not yet purchased this book. Would you like to purchase it now for '+data.result['amount']+'?', {title: 'Download', content: true, buttons: {'Yes': function(event){$(this).dialog("close").dialog("destroy"); purchaseEbook(productId, r); }, 'No': function(event){ $(this).dialog("close").dialog("destroy");}}});
				}
			}
			else if(data.error){
				// error detected
				if(data.error.code){
					overlay(data.error.message, {title: 'Download', content: true});
				}
				else {
					overlay(data.error, {title: 'Download', content: true});
				}
			}
			else{
				// unknown
			}
		}
	);
	
	return false;
}
function purchaseEbook(productId, r){
	$.getJSON('/rpc/', {method: 'purchaseEbook', params: $.param({productId: productId})}, function(data){
			if(data.result){
				// it worked
				overlay(data.result, {title: 'Purchase', content: true});
				window.location = 'd.php?r='+r;
			}
			else if(data.error){
				// error detected
				if(data.error.code){
					overlay(data.error.message, {title: 'Purchase', content: true});
				}
				else {
					overlay(data.error, {title: 'Purchase', content: true});
				}
			}
			else{
				// unknown
			}
		}
	);
	
	return false;
}
