// Business ID of Mattress
var bid=31;

$(document).ready(function(){
	$("#mypopup").hide();
	$("#emailme").click(function(){
		$("#mypopupcallus").hide();
		$("#mypopupemailus").hide();
		$("#mypopup").centerInClient();
		$("#mypopup").show();
		return false;
	});
	
	$("#emailme2").click(function(){
		$("#mypopupcallus").hide();
		$("#mypopup").hide();
		$("#mypopupemailus").centerInClient();
		$("#mypopupemailus").show();
		return false;
	});
	
	
	$("#callus").click(function(){
		$("#mypopup").hide();
		$("#mypopupemailus").hide();
		$("#mypopupcallus").centerInClient();
		$("#mypopupcallus").show();
		return false;
	});
	
}); // document close



function checkvalidationformail()
{
	if($("#visit_email_name2").val()=="")
	{
	alert("Please, enter your name");
	return false;
	}
	if($("#visit_email2").val()=="")
	{
	alert("Please, enter your email address");
	return false;
	}
	if(!isValidEmailAddress($("#visit_email2").val()))
	{
	alert("Please, enter a valid email address");
	return false;
	}
	
	if($("#visit_phone2").val()=="" || $("#visit_phone2").val()=="Number")
	{
	alert("Please, enter your phone number");
	return false;
	}
	if(!isTelephone($("#visit_phone2").val()))
	{
	alert("Please, enter valid numeric phone number\n formats: (XXX)YYY-ZZZZ , XXX-YYY-ZZZZ , XXXYYYZZZZ");
	return false;
	}
	if($("#visit_Coments2").val()=="")
	{
	alert("Please, enter your comments");
	return false;
	}
	var data = {
		"Name": $("#visit_email_name2").val(),
		"Email" : $('#visit_email2').val(),
		"Phone": $('#visit_phone2').val(),
		"Comments": $('#visit_Coments2').val(),
		"Product": $('#popupProductNameHidden').val()
	};
	$("#mypopup").hide();
	$("#mypopupemailus").hide();
	tb_show("Sending The Mail","#TB_inline?height=250&width=300&inlineId=mail_loading",null);
	$.post($("#themename").val()+"/productenquirymailer.php",data, callBackProductEnquiry);		
}


function callBackProductEnquiry(response){
	$("#TB_closeWindowButton").trigger('click');	 
	setTimeout(function(){			
		if(response==1)
			{
				_mw._trackAction('6', '|' + $('#visit_phone2').val()+ '|' + $('#visit_email2').val() + '|' + $("#visit_email_name2").val() + '|1|' + $('#visit_Coments2').val() + '|' + $('#popupProductNameHidden').val());	
				alert("Thanks! Your email has been sent.");		
			}
		else
			{
				alert("Sorry! Mail has not beed sent successfuly.");
			}	
		resetMyPopUp();
	}, 200);		
}



function checkvalidationformail2()
{
	if($("#visit_email_name").val()=="")
	{
	alert("Please, enter your name");
	return false;
	}
	if($("#visit_email").val()=="")
	{
	alert("Please, enter your email address");
	return false;
	}
	if(!isValidEmailAddress($("#visit_email").val()))
	{
	alert("Please, enter a valid email address");
	return false;
	}
	if($("#visit_Coments").val()=="")
	{
	alert("Please, enter your comments");
	return false;
	}
	if(!($("#special_number").val()=="" || $("#special_number").val()=="Number"))
	{
		if(!isTelephone($("#special_number").val()))
		{
		alert("Please,enter valid numeric phone number\n formats: (XXX)YYY-ZZZZ , XXX-YYY-ZZZZ , XXXYYYZZZZ");
		return false;
		}
	}
	$("#mypopup").hide();
	$("#mypopupemailus").hide();
	tb_show("Sending The Mail","#TB_inline?height=250&width=300&inlineId=mail_loading",null);
	 $("#formated_comment").load($("#themename").val()+"/format_comments.php?"+$("#frmMat").serialize(), callBackReplaceIdWithName);
	/*if($("#pagename").val() == "Home"){
		$.get('../../stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
		//$.get('./../Stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
	}else{
		$.get('../../../stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
		//$.get('./../../Stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
	} */	
}
function callBackReplaceIdWithName()
{
	$("#visit_Coments").val($("#formated_comment").html());
	if($("#pagename").val() == "Home"){
		$.get('../../stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
		//$.get('./../Stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
	}else{
		$.get('../../../stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
		//$.get('./../../Stats/mainMail.php?bid=' + bid + '&' + $("#frmMat").serialize(),callBackSendMail);
	}		
}
function callBackSendMail(response){
	$("#TB_closeWindowButton").trigger('click');	 
	setTimeout(function(){		
		if(response==1)
		{
		 	_mw._trackAction('3', $('#visit_email').val() +'|'+ $('#visit_Coments').val() + '|' + $("#visit_email_name").val());
		 	alert("Thanks! Your email has been sent.");
		}
	else
		{
			alert("Sorry! Mail has not beed sent successfuly.");
		}	
	resetMyPopUp();
	}, 200);		
}



function checkvalidation()
{
if($("#visit_name").val()=="" || $("#visit_name").val().match("Name"))
{
alert("Please, enter your name");
return false;
}
if($("#visit_number").val()=="" || $("#visit_number").val()=="Number")
{
alert("Please, enter your phone number");
return false;
}
if(!isTelephone($("#visit_number").val()))
{
alert("Please,enter valid numeric phone number\n formats: (XXX)YYY-ZZZZ , XXX-YYY-ZZZZ , XXXYYYZZZZ");
return false;
}
$("#inputboxes").hide();
$("#messagebox").show();
$("#mypopupcallus").hide();
tb_show("Sending The Mail","#TB_inline?height=250&width=300&inlineId=mail_loading",null);
if($("#pagename").val() == "Home"){
	$.get('../../stats/mainMail.php?bid='+bid+'&cb=1&sitename='+$("#sitename2").val()+'&'+ $("#frmMat").serialize(),callBackCallYou);	
	//$.get('./../Stats/mainMail.php?bid='+bid+'&cb=1&sitename='+$("#sitename2").val()+'&'+ $("#frmMat").serialize(),callBackCallYou);	
}else{
	$.get('../../../stats/mainMail.php?bid='+bid+'&cb=1&sitename='+$("#sitename2").val()+'&'+ $("#frmMat").serialize(),callBackCallYou);
	//$.get('./../../Stats/mainMail.php?bid='+bid+'&cb=1&'+ $("#frmMat").serialize(),callBackCallYou);
}

}

function callBackCallYou(response)
{	
	$("#TB_closeWindowButton").trigger('click');	 
	setTimeout(function(){		
		if(response==1)
		{			
			_mw._trackAction('2', $('#visit_name').val() +'|'+ $('#visit_number').val());			
			alert("Thanks! You will receive a call back during normal business hours.");
		}
	else
		{
			$("#TB_window").remove();
			alert("Sorry! Mail has not beed sent successfuly.");		
		}
	$("#visit_name").val("");
	$("#visit_number").val("");	
	resetMyPopUp();
		
	}, 200);			
}

function thanksmsg(){
$("#visit_name").val("Name");
$("#visit_number").val("Number");
$("#messagebox").hide();
$("#inputboxes").show();
}


function chkAjaxCall(RandomNo,StoreName)
	{

		_mw._trackAction('4', RandomNo+'|'+StoreName);
 		// $.get('./stats/mainMail.php?bid='+bid+'&RN='+RandomNo+'&sitename='+$("#sitename").val());
		window.print();
		
	}

function chkAjaxCallPrint(RandomNo,StoreName)
	{

		_mw._trackAction('4', RandomNo+'|'+StoreName);
 		// $.get('./stats/mainMail.php?bid='+bid+'&RN='+RandomNo+'&sitename='+$("#sitename").val());
		window.print();
		
	}

function settleCoupon(){
		var COOKIE_DATE = 'msdate';
		var COOKIE_MATTRESS = 'msselection';
        var options = { path: '/', expires: 7 };
 		if($.cookie(COOKIE_DATE)== null){
			//if first time user
			$.cookie(COOKIE_DATE, new Date(), options);
			$.cookie(COOKIE_MATTRESS, $("#coupontxt1").val(), options);
			var myDate=new Date();
			myDate.setDate(myDate.getDate()+7);
			$(document).ready(function(){
					$("#expdate2").text(myDate.toDateString());				   
			});
			return $("#coupontxt1").val();
		}
		else{
			//calculate remaining days
			var dt1=new Date();
			var dt2 = new Date($.cookie(COOKIE_DATE));
			var remday=6- parseInt(days_between(dt1,dt2));
			
			var myDate=new Date($.cookie(COOKIE_DATE));
			myDate.setDate(myDate.getDate()+7);
			//alert(myDate);
			$(document).ready(function(){
					$("#expdate2").text(myDate.toDateString());				   
			});
			
			$("#couponmsg").html('You have already made your selection <br /> Check back after ' + remday + ' day(s) for your new coupon offer');
			return $.cookie(COOKIE_MATTRESS);
			
		}
		return false;
}

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}



function resetMyPopUp()
{
	$("#visit_Coments").val("");
	$("#visit_email").val("");
	$("#visit_name").val("");
	$("#visit_number").val("");
	$("#visit_email_name").val("");
	$("#visit_phone2").val("");
	$("#visit_Coments2").val("");
	$("#visit_email2").val("");
	$("#visit_email_name2").val("");
	$("#mypopup").hide();
	$("#mypopupemailus").hide();
	$("#mypopupcallus").hide();
}

function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}

function isTelephone(number){
var pattern = new RegExp(/^(\()?([0-9]{3})(\)|-)?([0-9]{3})(-)?([0-9]{4}|[0-9]{4})$/);
return pattern.test(number);
}

function isNumeric(value) 
{ 
    if (value.match(/^\d+$/) == null) 
        return false; 
    else 
        return true; 
} 


/// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
	///<site>http://www.west-wind.com/weblog/posts/459873.aspx<site/>
    /// <returns type="jQuery" />
$.fn.centerInClient = function(options) {
    
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}
