/**
 * cmv3.js
 *-------------------------
 *
 * js base class
 *
 * PHP versions 5
 *
 * LICENSE: This source file is from CouponMountain Ver3.
 * The copyrights is reserved by http://www.mezimedia.com.
 * Copyright (c) 2006, Mezimedia. All rights reserved.
 *
 * @author     James.Huang <james_huang@mezimedia.com>
 * @copyright  (C) 2004-2006 Mezimedia.com
 * @license    http://www.mezimedia.com  PHP License 5.0
 * @version    CVS: $Id: cmv3.js,v 1.16 2007/12/25 00:11:54 james_huang Exp $
 * @link       http://www.couponmountain.com/
 * @deprecated File deprecated in Release 3.0.0
 */
 
var ScrollBase = {
	interval : null,

	init : function(func , speed , jobj){
		var element = this ;
		if(this.interval) clearTimeout(this.interval) ; 
		this.interval = setInterval( function (){ func(element , jobj) } , speed );
	},

	avMove : function(element, jobj) {
		var nowStart =  (element.style[jobj.moveStyle] == '') ? 0 : parseInt(element.style[jobj.moveStyle]);
		jobj.than = jobj.than ? jobj.than : 20;
		jobj.moveEnd = parseInt(jobj.moveEnd);
		jobj.avMoveStep = jobj.avMoveStep ? jobj.avMoveStep : (jobj.moveEnd - nowStart)/jobj.than;
		var zf = jobj.avMoveStep/Math.abs(jobj.avMoveStep);
		element.style[jobj.moveStyle] = nowStart + jobj.avMoveStep  + 'px';
		if((zf > 0 && parseInt(element.style[jobj.moveStyle]) >= jobj.moveEnd) || (zf < 0 && parseInt(element.style[jobj.moveStyle]) <= jobj.moveEnd)) {
			clearTimeout(element.interval);
			jobj.avMoveStep = 0;
		}
	},

	stepMove : function(element , jobj) {
//		alert(element.style[jobj.moveStyle]);
		var nowStart =  (element.style[jobj.moveStyle] == '') ? 0 : parseInt(element.style[jobj.moveStyle]);
		jobj.moveEnd = parseInt(jobj.moveEnd);
		var moveValue = jobj.moveEnd - nowStart;
		var step = (moveValue > 0) ? Math.ceil(moveValue/10) : Math.floor(moveValue/10);
		element.style[jobj.moveStyle] = nowStart + step  + 'px';
		if(jobj.moveEnd == parseInt(element.style[jobj.moveStyle]))
			clearTimeout(element.interval);
	},

	alphaShow : function (element , jobj) {
		if(getOpacity(element) >= (jobj.alpha ? jobj.alpha : 100)) {
			clearTimeout(element.interval);
			if(jobj && jobj.func.constructor == Function) jobj.func();
		}
		setOpacity(element , getOpacity(element) + 10);
	},

	alphaHide : function (element , jobj) {
		if(getOpacity(element) <= (jobj.alpha ? jobj.alpha : 0)) {
			clearTimeout(element.interval);
			if(jobj && jobj.func.constructor == Function) jobj.func();
		}
		setOpacity(element , getOpacity(element) - 10);
	}
}

Object.extend(ScrollBase, JBase);

var mainDomainName = location.protocol+location.port+"//"+location.host;

var CM = Class.create();
Object.extend(Object.extend(CM, JBase), {
	initialize: function() {
		this.Version = 'v_3';
	},

	redirect: function (url) {
		window.location = url.escapeQuote();
	},

	emailTo: function (pid) {
		window.open('/send_friend.php?p=' + pid, 'sendfriend' + pid, 'width=500, height=550, resizable=0, scrollbars=yes');
	},

	openout: function (url) {
		window.open(url, '', '', '');
	},

	sayHello: function () {
		var member = getCookie("Member");
		if (member != null)
			$('hello').innerHTML = "<h2><strong>Hello " + member + "<\/strong>! Find free voucher codes, bargains and sales<br \/>from more than 500 online stores. <a href=\"/all_merchant.html\" class=\"ud\">See vouchers &amp; deals by store<\/a><\/h2>";
	},

	myAccount: function () {
		var member = getCookie("Member");
		if ($('account') && member != null)
			$('account').innerHTML = '<h3 class="accounttop">My Account</h3><ul class="logOut">'
				+ '<li>Name: <span class="bluedark">' + member + '</span></b> </li>'
				+ '<li>Coupons Saved: <span class="bluedark">' + getCookie("savedCouponSum") + '</span></li>'
				+ '<li class="logPgOut">Coupon Alert: <span class="red">' + getCookie("isSubscribe") + '</span></li>'
				+ '<li class="logbdOut"><a href="/account.php" class="ud">My Account Summary</a></li>'
				+ '<li><a href="/register.php?act=modify" class="ud">Modify Account</a></li>'
				+ '<li><a href="/register.php?act=Logout" class="ud">Log Out</a></li></ul>';
	},

	readMore: function () {
//		Element.hide("shortmerintro");
//		Element.show("longmerintro");
		$('shortmerintro').className = "disn";
		$('longmerintro').className = "";
	},

	hideInfo: function () {
//		Element.hide("longmerintro");
//		Element.show("shortmerintro");
		$('shortmerintro').className = "";
		$('longmerintro').className = "disn";
	},

	scrollMarquee: function (element, num, width, add, nowPage) {
		var parentElement = $('scrollFrame');
		var baobao = getElementsByClassName(parentElement, 'div', 'scrollInner')[0];
		//page and value
		var iptElement = $('featurePage');
		var valueArr = iptElement.value.split('v');
		var page = eval(valueArr[0]);
		var totalPage = eval(valueArr[1]);
		var nowPage = nowPage ? nowPage : (page + add);
		if(nowPage < 1 || nowPage > totalPage ) return false;
		iptElement.value = nowPage + 'v' + totalPage;
//		alert(iptElement.value);
		// extend and src
		var blockWidth = num * width;
		var divArr = baobao.getElementsByTagName('div');
		if(!baobao.Author) {
			Object.extend(baobao, ScrollBase);
		}
		baobao.init(baobao.stepMove , 2 , {moveStyle : 'marginLeft', moveEnd : -1 * blockWidth * (nowPage - 1)});
	},

	subinput: function (obj, id) {
		if(obj.checked==true){
			document.getElementById('checkBg'+id).className='subyellow';
		}else{
			document.getElementById('checkBg'+id).className='';
		}
	},

	dropdown: function (e, sign) {
		if ($('dropdownbtn')) {
			var obj = null;
			if (window.event) {
				if (sign) {
					obj = event.fromElement;
				} else {
					obj = event.toElement;
				}
			} else {
				obj = e.relatedTarget;
			}
			while (obj!=null && obj.id!='dropdownbtn') {
				obj = obj.parentNode;
			}
//			if (obj!=null) alert(obj.id);
			if (obj==null) {
				if (sign) {
					$('dropdown').className = $('dropdown').className.replace(" disn", "");
				} else {
					var myReg = /\s*disn\s*/;
					if (!myReg.test($('dropdown').className)) {
						$('dropdown').className = $('dropdown').className + " disn";
					}
				}
				return true;
			}
		}
		return false;
	},

	copyToClip: function (text2copy) {
//		if (window.clipboardData) {
//			window.clipboardData.setData("Text",text2copy);
//		} else {
			var flashcopier = 'flashcopier';
			if(!document.getElementById(flashcopier)) {
				var divholder = document.createElement('div');
				divholder.id = flashcopier;
				document.body.appendChild(divholder);
			}
			document.getElementById(flashcopier).innerHTML = '';
			var divinfo = '<embed src="/js/default/clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
			document.getElementById(flashcopier).innerHTML = divinfo;
//			alert('Text copied');
//		}
	},

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// validate funcitons

	check_mail: function (vemail) {
		if (vemail.value == ""){
			alert("Please enter email address"); 
			return false;
		} else {
			var gem = vemail.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
			if (!gem) {
				alert("Please enter a valid email address");
				vemail.focus();
				vemail.select();
				return false;
			} else {
				return true;
			}
		}
	},

	// check auth before enter account.php
	checkAccount: function (redirect_url) {
		var url = mainDomainName + '/account.php?ar=1';
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert('Saving ...', {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					myAlert(message);
				} else {
					window.location = redirect_url;
				}
			}
		});
	},

	checkAccountForm: function () {
		var fom = 'accountForm';
		var url = mainDomainName + '/register.php?' + $(fom).serialize();
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert('Logging in ...', {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					$(fom).submit();
				}
			}
		});
	},

	checkFormRequest: function () {
		var fom = 'form_request';
		var url = mainDomainName + '/request.php?' + $(fom).serialize();
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert('Sending your request ...', {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					setTimeout("window.location.href='/'", 10000);
					myAlert('Mail has been sent successfully.<br/>This page will redirect to index in 10 seconds.', {
						form: '',
						focuson: '',
						redir_url: '/',
						btn_str: 'Back To Home'
					});
				}
			}
		});
	},

	checkFormSubmit: function () {
		var fom = 'form_submit';
		var url = mainDomainName + '/submit.php?' + $(fom).serialize();
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert('Sending your request ...', {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					setTimeout("window.location.href='/'", 10000);
					myAlert('Mail has been sent successfully.<br/>This page will redirect to index in 10 seconds.', {
						form: '',
						focuson: '',
						redir_url: '/',
						btn_str: 'Back To Home'
					});
				}
			}
		});
	},

	checkFormTellFriend: function () {
		var friend	= $("friend");
		var email	= $("email");
		var name	= $("name");
		if (friend.value == "" || (name.value == "" && email.value == "")){
			alert("Please fill completely !");
		} else {
			if (friend.value != ""){
				if (!this.check_mail(friend))
					return false;
			}
			if (!this.check_mail(email))
				return false;
			else
				$('form_tell_fried').submit();
		}
	},
	
	checkContactUsInfo: function () {
		
		var form = 'form_contactus';
		var url = mainDomainName + '/contactus.php';
		//var url = mainDomainName + '/contactus.php?' + $(form).serialize();
		
		var name = $('name') ? $('name').value : '';
		var email = $('email') ? $('email').value : '';
		var ftypevalue = $('ftypevalue') ? $('ftypevalue').value : '';
		var maildescription = $('maildescription') ? $('maildescription').value : '';
		var sCode = $('sCode') ? $('sCode').value : '';
		var referpage = $('referpage') ? $('referpage').value : '';

		var pars = 'act=contactus&name='+name+'&email='+email+'&ftypevalue='+ftypevalue+'&maildescription='+encodeURIComponent(maildescription)+'&sCode='+sCode+'&referpage='+referpage;
				
		var loading_info = 'Sending Email ...';
		var complete_info = 'Thank you for submitting your feedback to CouponMountain UK,we appredate your response.';
		var complete_redir_url = '/';
		new Ajax.Request(url, {
			method: 'post',
			parameters: pars,
			asynchronous: true,
			onLoading: function() {
				myAlert(loading_info, {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: form,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					myAlert(complete_info, {
						form: '',
						focuson: '',
						redir_url: complete_redir_url,
						btn_str: 'Back to Homepage'
					});
				}
			}
		});
		
	},

	verifyImgRefresh: function () {
		
		var url = mainDomainName + '/verifyimg.php';
		
		var sCode = CM.getfRandomBy(1,99); 
	
		var pars = '?securityCode='+sCode;
		
		var eleVerifyImg = document.getElementById("verify_img");

		new Ajax.Request(url, {
			method: 'get',
			parameters: pars,
			asynchronous: true,

			onSuccess: function(transport) {	
				
				var notice = transport.responseText;

				if (notice!='error') {
					
					eleVerifyImg.src = notice;
					//document.form_contactus.sCode.focus();
				} 
			}
		});
		
	},

	getfRandomBy: function (under, over) {
	
		switch(arguments.length){
			case 1: return parseInt(Math.random()*under+1);
			case 2: return parseInt(Math.random()*(over-under+1) + under);
			default: return 1;
		}
	},

	checkRegInfo: function (typ) {
		var fom = 'form_register';
		var url = mainDomainName + '/register.php?' + $(fom).serialize();
		var loading_info = 'Registering ...';
		var complete_info = 'Registered successfully, please check your email and click the confirm url to active your account.';
		var complete_redir_url = '/';
		// modify form validate
		if (typ == "modify") {
			var loading_info = 'Saving your changes ...';
			var complete_info = 'Your Account has been updated successfully.';
			var complete_redir_url = '/account.php';
		}
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert(loading_info, {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					myAlert(complete_info, {
						form: '',
						focuson: '',
						redir_url: complete_redir_url
					});
				}
			}
		});
	},

	// check send password
	checkSendPassword: function (redirect_url) {
		var fom = 'form_forgot';
		var url = mainDomainName + '/register.php?' + $(fom).serialize();
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert('Sending Password ...');
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: '/register.php?e=mail'
					});
				} else {
					myAlert('Your Password has been sent to your Email.', {
						form: '',
						focuson: '',
						redir_url: '/'
					});
				}
			}
		});
	},

	// check unsubscribe
	checkUnsubscribe: function (redirect_url) {
		var fom = 'form_forgot';
		var url = mainDomainName + '/register.php?' + $(fom).serialize();
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onLoading: function() {
				myAlert('Checking Email ...');
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					myAlert('Your have been successfully unsubscribed.', {
						form: '',
						focuson: '',
						redir_url: '/'
					});
				}
			}
		});
	},

	// check coupon comment
	checkCommentForm: function (redirect_url, isLogin) {
		var fom = 'form_comment';
		var isLogin = (isLogin) ? isLogin : false;
		if (isLogin) {
			if ($(fom)) $(fom).login.value = "yes";
		} else {
			if ($(fom)) $(fom).login.value = "no";
		}
		var url = mainDomainName + '/coupon.php';
		new Ajax.Request(url, {
			method: 'post',
			asynchronous: true,
			parameters: $(fom).serialize(),
			onLoading: function() {
				myAlert('Check comment ...', {loading: true});
			},
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					var message = (notice.match(/@/gi)) ? notice.slice(notice.indexOf(':') + 1, notice.indexOf('@')) : notice.slice(notice.indexOf(':') + 1);
					var focuson = (notice.match(/@/gi)) ? notice.slice(notice.indexOf('@') + 1) : '';
					myAlert(message, {
						form: fom,
						focuson: focuson,
						redir_url: ''
					});
				} else {
					setTimeout("window.location.href='" + redirect_url.escapeQuote() + "'", 5000);
					myAlert('Your comment has been successfully received. It will be posted on the site momentarily.', {
						form: '',
						focuson: '',
						redir_url: redirect_url,
						btn_str: 'Close'
					});
				}
			}
		});
	},

	checkCommentFormEmail : function() {
		var email = ($('email') && $('email').value != '') ? $('email').value : 'unknown';
		var url = mainDomainName + '/coupon.php?checkEmail=' + email;
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onSuccess: function(transport) {
				var notice = transport.responseText;
				if (notice.match(/^\[error_message\]:/gi)) {
					$('user_password').className = $('user_password').className.replace(" disn", "");
					$('login_and_commit').className = $('login_and_commit').className.replace(" disn", "");
				} else {
					$('user_password').className = "user_password disn";
					$('login_and_commit').className = "login_and_commit disn";
				}
			}
		});
	},

	couponFeedback : function(couponid, ishelpful, redirect_url) {
		var url = mainDomainName + '/feedback.php?couponid='+couponid+'&ishelpful='+ishelpful;
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onSuccess: function(transport) {
				var notice = transport.responseText;
				setTimeout("window.location.href='" + redirect_url.escapeQuote() + "'", 5000);
				if(notice == 'success'){ //todo
					myAlert('Thank you for your feedback! If there is an error, a CouponMountain editor will be notified.',{
						form: '',
						focuson: '',
						redir_url: redirect_url,
						btn_str: 'Close'
					});
				}else{
					myAlert('You have voted this offer!');
				}
			}
		});
	},

	/////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// notify_me funcitons

	addm: function (form_name, listto, listfrom) {
		var tmpValue;
		var selValue;
		var selText;
		var fromlen;
		var selitem;
		var len;
		eval("fromlen=window.document.forms['" + form_name + "']." + listfrom + ".length");
		for (var j=0; j<fromlen; j++){
			eval("selitem=window.document.forms['" + form_name + "']." + listfrom + "[" + j + "].selected");
			if (selitem){
				selIndex = j;
				eval("selValue=window.document.forms['" + form_name + "']." + listfrom + ".options[" + selIndex + "].value");
				eval("selText=window.document.forms['" + form_name + "']." + listfrom + ".options[" + selIndex + "].text");
				eval("len=window.document.forms['" + form_name + "']." + listto + ".length");
				for (var i=0; i < len; i++){
					eval("tmpValue=window.document.forms['" + form_name + "']." + listto + ".options[" + i + "].value");
					if ( tmpValue == selValue ){break;}
				}
				if ( tmpValue != selValue ) {
					var opt = new Option(selText,selValue);
					eval("window.document.forms['" + form_name + "']." + listto + ".options[" + "window.document.forms['" + form_name + "']." + listto + ".length]=opt");
				}
			}
		}
	},
	
	removem: function (form_name, listfrom) {
		var arrstr = "0";
		eval("fromlen=window.document.forms['" + form_name + "']." + listfrom + ".length");
		for (var j=0; j<fromlen; j++) {
			eval("selitem=window.document.forms['" + form_name + "']." + listfrom + "[" + j + "].selected");
			if (selitem){
				selIndex = j;
				eval("selValue=window.document.forms['" + form_name + "']." + listfrom + ".options[" + selIndex + "].value");
				arrstr = arrstr + ',' + selValue;
			}
		}
		eval("selItem=new Array(" + arrstr + ")");
		for (var j=0; j<selItem.length; j++) {
			eval("len=window.document.forms['" + form_name + "']." + listfrom + ".length");
			for (var i=0; i < len; i++) {
				eval("tmpValue=window.document.forms['" + form_name + "']." + listfrom + ".options[" + i + "].value");
				if ( selItem[j] == tmpValue ){
					eval("window.document.forms['" + form_name + "']." + listfrom + ".options[" + i + "] = null");
					break;
				}
			}
		}
	},
	
	list2str: function (form_name, listfrom, strto) {
		var result = "";
		var tmpValue = "";
		eval("len=window.document.forms['" + form_name + "']." + listfrom + ".length");
		for (i=0; i < len; i++) {
			eval("tmpValue=window.document.forms['" + form_name + "']." + listfrom + ".options[" + i + "].value");
			result = result + tmpValue + ";";
		}
		eval("window.document.forms['" + form_name + "']." + strto + ".value='" + result + "'");
	}
	
});

/* Prevent to be iframed */
if(self!=top){top.location=self.location;}