//use diff variable to reference jQuery
var jq = jQuery;

function hrefto(loc){
	window.location = loc;
}
function stringFormat(str, parms){
    var tmp = str;
    for(var i=0;i<parms.length;i++){
        tmp = replaceAll(tmp, '{'+i+'}', parms[i]);
    }
    return tmp;
}

function replaceAll(str, from, to){
    var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    return str;
}

function TrimString(str) {
    str = str.replace(/^[ ]+(.*)$/, '1'); // Trims leading spaces
    str = str.replace(/^(.*)[ ]+$/, '$1'); // Trims trailing spaces
    return str;
}

function quickformsubmit(kvpairs, page, target, conf){
    var qfid = "quickform_"+Math.round(Math.random()*10000);//must round because somehow a decimal in the number breaks the id or something
    
    if(!page)
        page = window.location;
    if(!target)
        target = "_self";
    var formtop = "<form method=\"post\" id=\""+qfid+"\" name=\""+qfid+"\" action=\""+page+"\" target=\"" + target + "\">";
    if(conf){
        if(!confirm("are you sure?"))
            return;
    }
    for(var i=0;i<kvpairs.length;i++){
        
        formtop+= "<input type=\"hidden\" name=\""+kvpairs[i][0]+"\" value=\""+kvpairs[i][1]+"\" />";
    }
    formtop+= "</form>";
    //alert(formtop);
    jQuery("body").append(formtop);
    //alert(jQuery("#"+qfid).size());
    //jQuery("#"+qfid).get(0).submit();
    document.forms[qfid].submit();

}
//count a string and count the newlines as two
function countStringLength(str){
    var nlcount = str.split(/\n|\r/).length;
    if(document.selection)
        return str.length;
    else
        return nlcount - 1 + str.length;
    
}
//get texts area position
//function GetCaretPosition (ctrl) {

//	var CaretPos = 0;
//	// IE Support
//	if (document.selection) {

//		ctrl.focus();
//		var r = document.selection.createRange();

//        var re = ctrl.createTextRange();
//		var rc = re.duplicate();
//		re.moveToBookmark(r.getBookmark());
//        rc.setEndPoint('EndToStart', re);		

//		CaretPos = rc.text.length;
//	}
//	// Firefox support
//	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
//		CaretPos = ctrl.selectionStart-1;

//	return (CaretPos);

//}
////set textarea position
//function setCaretPosition(ctrl, pos)
//{

//	if(ctrl.setSelectionRange)
//	{
//		ctrl.focus();
//		ctrl.setSelectionRange(pos,pos);
//	}
//	else if (ctrl.createTextRange) {
//		var range = ctrl.createTextRange();
//		range.collapse(true);
//		range.moveEnd('character', pos);
//		range.moveStart('character', pos);
//		range.select();
//	}
//}
function UpdateMessageBoxUI(jo){
   if(!jo.value){
    jo = this;
    }
	var msg = jo.value;				
	//var startpoint = GetCaretPosition(jo);	
	//alert(startpoint);
	    //take out traitorous characters  {,},[,],^,~,\,|
	    /*if(msg.indexOf("{")>-1 || msg.indexOf("}")>-1 ||msg.indexOf("[")>-1 ||msg.indexOf("]")>-1 ||msg.indexOf("^")>-1 ||msg.indexOf("~")>-1 ||msg.indexOf("\\")>-1 ||msg.indexOf("|")>-1){
	    msg = replaceAll(msg,"{","");
	    msg = replaceAll(msg,"}","");
	    msg = replaceAll(msg,"[","");
	    msg = replaceAll(msg,"]","");
	    msg = replaceAll(msg,"^","");
	    msg = replaceAll(msg,"~","");
	    msg = replaceAll(msg,"\\","");
	    msg = replaceAll(msg,"|","");
	    
	      jo.value=msg;
	    }*/
	    if(msg.match(/[^\w|\r|\n| |!|@|#|$|%|&|*|(|)|\-|=|+|:|;|"|'|?|\/|>|<|.|,]/gi)){
	        msg = msg.replace(/[^\w|\r|\n| |!|@|#|$|%|&|*|(|)|\-|=|+|:|;|"|'|?|\/|>|<|.|,]/gi,'');	    
	        jo.value=msg;
	        //setCaretPosition(jo, Math.min(countStringLength(msg), Math.abs(startpoint)));
//alert(startpoint);
            //setCaretPosition(jo, startpoint);
	    }
	   
	   //check message length after removal of nonstandard characters and reset if its over
	    var txtlmt = 160;
	    var msglmt = 480;
	    while(countStringLength(msg)>msglmt){
	        msg = msg.substr(0, msg.length -1);
	        jo.value=msg;	        
	    }
	    
	    
	    //finally set the text area back to what it is cleaned to UPDATE: no this moves cursor to the end all the time
	  
	    
	var multiple = Math.ceil(countStringLength(msg)/txtlmt);
	var newmax = txtlmt*multiple;
	var uitemplate = "<div class='clearfix msgboxui'><div class=''>Using&nbsp;<b>[{0}]</b>&nbsp;text(s)</div><div class=''>{1}/{2}&nbsp;characters used</div></div>";
	var fin = stringFormat(uitemplate, [multiple, countStringLength(msg), newmax]);
	jq(jo).parent().find(".msgboxui").remove();
	jq(jo).after(fin);
}
function checkActionListSelect(elid){
        var el = jq('#'+elid);
        if(el.val()=="newlist"){
	        el.after("<span class='newlistinputdiv'><br/>new list name: <input type='text' name='listname' /></span>\
	                    <div class='attachkeywordbox' style='display:none;position:relative;'>\
                            <a href='javascript:void(0);' onclick='jq(this).parent().find(\".attachkeywordsubbox\").toggle();'>\
                                +attach a combo word</a>\
                                <a href='#' OnMouseOver='addkeywordhelpnugget(this);' OnMouseOut=''><b>(?)</b></a>\
                            <div class='attachkeywordsubbox' style='display: none;'>\
                                <label>\
                                    combo word:</label><input type='text' name='keyword' maxlength='10' onkeydown='jq(this).val(replaceAll(this.value, \" \", \"\"));' />\
                            </div>\
                        </div>");
	        jq('.attachkeywordbox').show();
	        }
        else{
	        jq('.newlistinputdiv,.attachkeywordbox').remove();//used to have multiple attachkeywordbox elements popping up here
	        el.parent().find('.attachkeywordbox').hide();
	        }
    }
    function addkeywordhelpnugget(el){
        jq(el).parent().find('.keywordhelpnugget').remove();//first take it out
        var nuggethtml="<div OnMouseOut='' class='keywordhelpnugget'>A combo word helps your customers enter campaigns and join lists. Create a combo word and tell customers to text:<br /> <b>'"+(!getCookie("username")?"USERNAME":getCookie("username").toUpperCase())+" [combo word]'</b> to <b>39970</b>. Learn more <a href='/help/acbkeywords/' targer='_blank' style='text-decoration:underline;color:white;'>here</a><br/><small style='border:1px white solid;padding:0 2px;' OnMouseOver='removekeywordhelpnugget(this);'>close</small></div>";
        //var newhtml = jq(el).html() + nuggethtml;
        jq(el).after(nuggethtml);
    }
    function removekeywordhelpnugget(el){
        //jq(el).parent().find('.keywordhelpnugget').remove();
        jq('.keywordhelpnugget').remove();
    }
    
function UpdateTimeToNow(nowlink){
//what are the time variables for now...hr, min, meridian
	var theDate = new Date();
	var iHour = theDate.getHours();
	var iMin = theDate.getMinutes();
	var minuteblox = Math.floor(iMin/5);
	if(minuteblox>11){
		iHour = iHour+1;
		iMin = 0;
	}else{
		iMin = minuteblox*5;
	}
	var iXm = (iHour>11?"pm":"am");
	
	//now set hour to non-military value
	if(iHour>12)
		iHour = iHour-12;
	if(iHour==0)
		iHour=12;
	
	//alert(iHour + ":"+iMin+":"+iXm);
	//alert(selectsintable.size());
    //now set them for those 3 selects accordingly
	
	//var selectsintable = jq(nowlink).parent().parent().parent().find("select");
	
	var msgform = jq(nowlink).parents("form");
	var selectsintable = msgform.find("select");
	
	if(!(selectsintable.size()>=3)){
		alert("cannot set time to now at the moment.");
		return;
	}else{
		//alert(selectsintable.get(0).val());
		//selectsintable.get(selectsintable.length-3).value=iHour;
		//selectsintable.get(selectsintable.length-2).value=iMin;
		//selectsintable.get(selectsintable.length-1).value=iXm;
		msgform.find("select.messagehour").val(iHour);
	    msgform.find("select.messageminute").val(iMin);
	    msgform.find("select.messagemeridian").val(iXm);
	}
    
}

//attach date/errors check for on submit, mostly date filled out.
jq(document).ready(function(){
			//onpageload find that form
			var formitemshere = jq("form select.messagehour, form textarea.txtmsgbody");
			//alert(formitem.size());
			if(formitemshere.size()>0){
			    for(var i=0; i<formitemshere.size();i++){
			        //if the textarea in this form 
			        var formitem = jq(formitemshere[i]);
			        var thetextarea = formitem.parents("form").find("textarea:last");
			        //if is empty add the business reminder tag
			        if(thetextarea.val()==""){
			            thetextarea.val("\n"+"-"+getCookie("userbusinessname"));			            			           			           

			         }			         
			         //attach updatemessageboxui events for all form-submitted text message bodies. the onkeyup event attached to each of the textareas in the actual aspx pages should now be deprecated as the "txtmsgbody" class is used to identify these things, except where time is set, hence the multiselector that precedes the precedes this forloop.UpdateMessageBoxUI is now overloaded as it can take in nothing or the actual textarea in question
			        thetextarea.keydown(UpdateMessageBoxUI).keyup(UpdateMessageBoxUI).mousemove(UpdateMessageBoxUI).mouseup(UpdateMessageBoxUI).mousedown(UpdateMessageBoxUI);
			        //now attach the submit function to it
			        formitem.parents("form").submit(messagesubmitcheck);
			    }
			    //maybe do cookie check and append  signature value of user IF there is no existing message (split join on it?)
			}
			
			if(jq('textarea.makenewmessage').size()>0){//any ta that you make anew message from, like plans/coupons should have the bizname in it
			    jq('textarea.makenewmessage').val("\n"+"-"+getCookie("userbusinessname"));			
			}
		});
		

var messagesubmitcheck = function(){
    
    //skip all of this if that checkbox is there but its NOT checked
    if(jq("#sendmessagecb").size()==1 && jq("#sendmessagecb[@checked]").size()==0){
        return true;
    }
    //get all the selects in the form(how about text area and the title, and the date)?
 
    var emptytime = false;
    jq(this).find("select.messagehour, select.messageminute, select.messagemeridian").each(function(){
        
        if(this.value == ""){
            emptytime = true;
        }
    
    });
    
    var baddate = false;
    jq(this).find(".messagedate").each(function(){
        if(this.value=="")
            baddate = true;
    });
    
    //comb body for bad characters and remove them, then set that back as the value of the textarea before it gets submitted
    var txtmsgbody = jq(this).find("textarea:last").val();
    txtmsgbody = txtmsgbody.replace(/[^\w|\r|\n| |!|@|#|$|%|&|*|(|)|\-|=|+|:|;|"|'|?|\/|>|<|.|,]/gi,'');
    var msglmt = 480;
	while(countStringLength(txtmsgbody)>msglmt){
	        txtmsgbody = txtmsgbody.substr(0, txtmsgbody.length -1);
	        
	}	
    jq(this).find("textarea:last").val(txtmsgbody);
    if(txtmsgbody==""){
        alert("Please type a message to send.");
        return false;
    }

    if(emptytime){
        alert("Please choose an hour, minute and am/pm value to send this message.");
        return false;
    }
    if(baddate){
        alert("Please choose a date on which to send this message.");
        return false;
    }
    
    //return true;
    
}