// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function replaceAll(txt, replace, with_this) {
    if (txt != null) {
        return txt.replace(new RegExp(replace, 'g'), with_this);
    }
    else {
        return "";
    }
}

function strip(txt) {
  return txt.replace(/^\s+|\s+$/g,"");
}



function formatWithDecimals (n,decimals) {
      decimals=(decimals>=0?decimals:2)
    var t = Math.floor(n*Math.pow(10,decimals)+0.5).toString();
    while (t.length < decimals+1) t = "0"+t;
          var i = t.length-decimals;
      if(decimals)
          t = t.substr(0,i)+"."+t.substr(i); // insert decimal separator (a dot or comma)
    for (i -= 3; i > 0; i -= 3) 
            t = t.substr(0,i)+","+t.substr(i); // insert thousands separators (commas or dots)
    return t;
}


function two(x) {return ((x>9)?"":"0")+x}
function three(x) {return ((x>99)?"":"0")+((x>9)?"":"0")+x}

function time(ms) {
var sec = Math.floor(ms/1000)
ms = ms % 1000
t = three(ms)

var min = Math.floor(sec/60)
sec = sec % 60
t = two(sec) + ":" + t

var hr = Math.floor(min/60)
min = min % 60
t = two(min) + ":" + t



return t
}

function repositionInfoTab(){
	
		var offset = "50px";
		if (window.pageYOffset > 0) 
		{
			offset = window.pageYOffset;
		}
		jQuery("#info_message").css("top", offset);
		
	}
	function startProcess(text){
		repositionInfoTab();
		jQuery("#info_message").css("left", (jQuery(window).width() - text.length) / 2);
		jQuery("#info_message #text").html(text);
		jQuery("#info_message").show();
	}
	
	function endProcess(){
		jQuery("#info_message #text").html("");
		jQuery("#info_message").hide();
	}


function showModal(divId, title, height, width){
	
	
	
	showDialog(divId, title, height, width, {
					"Close" : function() {
						$(this).dialog("close");
						$(this).dialog("destroy");
					
					}
					
				}); 
	
	
	
}

/*function alert(message){
	$("#confirm").html(message);
	
		showDialog("confirm", "Alert", 100, 300, {
					
					"OK" : function() {
						$(this).dialog("close");
						$(this).dialog("destroy");
					}
					
				}); 
}*/

function confirm(message, callback, oncancel){
    
    jQuery("#sdblDialog").html(message);

    showDialog("sdblDialog", "Confirm", 80, 480, {
					"Cancel" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
						if (oncancel != null){
							oncancel();
						}
					
					},
					"OK" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
						if (callback != null) {
							callback();
						}
					
					}
					
				}); 
	
}


function upgrade(message){
	
	jQuery("#sdblDialog").html(message);
	if ($WL_ON == true && $wl_af_on == false) 
	{
		
		showDialog("sdblDialog", "You need to upgrade your account", 200, 550, {
					"Cancel" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
					
					}
					
				}); 
	}
	else 
	{
	showDialog("sdblDialog", "You need to upgrade your account", 200, 550, {
					"Cancel" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
					
					},
					"View Plans" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
						window.location="/upgrade";
						
					
					}
					
				}); 
	}

}


function viewplans(title, message) {

    jQuery("#sdblDialog").html(message);
    if ($WL_ON == true && $wl_af_on == false) {

        showDialog("sdblDialog", "You need to upgrade your account", 150, 580, {
            "Cancel": function () {
                jQuery(this).dialog("close");
                jQuery(this).dialog("destroy");

            }

        });
    }
    else {
        showDialog("sdblDialog", title, 150, 580, {
            "Cancel": function () {
                jQuery(this).dialog("close");
                jQuery(this).dialog("destroy");

            },
            "View Plans": function () {
                jQuery(this).dialog("close");
                jQuery(this).dialog("destroy");
                if ($WL_ON != true) {
                    window.location = "/upgrade?filter=allplans";
                }
                else {
                    window.location = "/upgrade";
                }


            }

        });
    }

}

function upgradeTopUp(message){
	
	if ($WL_ON == true && $AF_ON == false) 
	{
		if ( $WL_TOKENS  == true) {
			jQuery("#sdblDialog").html(message);

			showDialog("sdblDialog", "You need to add more credits", 150, 550, {
						"Cancel" : function() {
							jQuery(this).dialog("close");
							jQuery(this).dialog("destroy");
						
						},
						"Add Credits" : function() {
							jQuery(this).dialog("close");
							jQuery(this).dialog("destroy");
							window.location="/upgrade?filter=extras";
						
						}
						
					}); 
		}
		else 
		{
			jQuery("#sdblDialog").html(message);
			showDialog("sdblDialog", "You have used up all your message credits", 150, 550, {
						"Cancel" : function() {
							jQuery(this).dialog("close");
							jQuery(this).dialog("destroy");
						}
					}); 
		}
	}
	
	else {
	
	jQuery("#sdblDialog").html(message);
	
	showDialog("sdblDialog", "You need to add credits", 150, 550, {
					"Cancel" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
					
					},
					"Add Credits" : function() {
						jQuery(this).dialog("close");
						jQuery(this).dialog("destroy");
						window.location = "/upgrade?filter=extras";
					
					}
					
				}); 
	}
	
}

function showDialog(divId, title, height, width, buttons){
	
	var $dialog = jQuery("#" + divId);
	$dialog.dialog(
	{
		modal: true,
		title: title,
		width: width,
		height: height,
		buttons: buttons,
		close: function(){$dialog.dialog("destroy");}
	}
	).show();
	//tb_show(title, "#TB_inline?height="+height+"&width="+width+"&inlineId="+divId);
	
}

function showModalDialog(divId, title, height, width, buttons){
	
	var $dialog = jQuery("#" + divId);
	$dialog.dialog(
	{
		modal: false,
		title: title,
		width: width,
		height: height,
		buttons: buttons,
		close: function(){$dialog.dialog("destroy");}
	}
	).show();
	//tb_show(title, "#TB_inline?height="+height+"&width="+width+"&inlineId="+divId);
	
}

function showDialogContent(content, title, height, width, buttons){
	jQuery("#sdblDialog").html(content);
	var $dialog = jQuery("#sdblDialog");
	if (buttons == null){
		buttons = {"Close": function() {
			$dialog.dialog("destroy");}};
	}
	$dialog.dialog(
	{
		title: title,
		width: width,
		height: height,
		close: function(){$dialog.dialog("destroy");},
		modal: true,
		buttons: buttons
	}
	).show();
	
	//tb_show(title, "#TB_inline?height="+height+"&width="+width+"&inlineId="+divId);

}

function showDialogNote(title, to, buttons) {
    var content = "<table class=\"tbl\"><tr class=\"rw\"><td class=\"cll\" style=\"border-bottom:1px solid #C7D9E5;\"><b>Attach a note:</b> <img src=\"/images/help.png\" style=\"float:right;\"  class=\"dialog_note_help\" /></td></tr></table><table class=\"tbl\"><tr class=\"rw\"><td class=\"cll\"><textarea id=\"dialog_note\" style=\"width:530px;\"></textarea></td></tr></table>";
    jQuery("#imgDialog").html(content);
    var $dialog = jQuery("#imgDialog");
    if (buttons == null) {
        buttons = { "Close": function() {
            $dialog.dialog("destroy");
        } 
        };
    }
    $dialog.dialog(
	{
	    title: title,
	    width: 600,
	    height: 275,
	    close: function() { $dialog.dialog("destroy"); },
	    modal: true,
	    buttons: buttons
	}
	).show();

    //tb_show(title, "#TB_inline?height="+height+"&width="+width+"&inlineId="+divId);

}

function showDialogAlert(targetId, content, title, height, width, buttons){
	jQuery("#"+targetId).html(content);
	var $dialog = jQuery("#" + targetId);
	if (buttons == null){
		buttons = {"Close": function() {
			$dialog.dialog("destroy");}};
	}
	$dialog.dialog(
	{
		title: title,
		width: width,
		height: height,
		close: function(){$dialog.dialog("destroy");},
		buttons: buttons
	}
	).show();
	
	//tb_show(title, "#TB_inline?height="+height+"&width="+width+"&inlineId="+divId);
	
}

function showFlashDialog(title, html, width, height) {

	jQuery("#imgDialog").html(decodeURIComponent(html));
	
	var $dialog = jQuery("#imgDialog");
	
		var buttons = {"Close": function() {
			$dialog.dialog("destroy");}};
	
	$dialog.dialog(
	{
		title: title,
		close: function(){$dialog.dialog("destroy");},
		buttons: buttons,
		width: width,
		height: height
	}
	).show();
}

function showImageDialog(title, url, width, height) {

	jQuery.facebox("<img src=\""+url+"\" style=\"text-align:center;max-height: 800px;\"/>");
	return;
	jQuery("#imgDialog").html("<img src=\""+url+"\" style=\"text-align:center;max-height: 800px;\"/>");
	
	var $dialog = jQuery("#imgDialog");
	
		var buttons = {"Close": function() {
			$dialog.dialog("destroy");}};
	
	$dialog.dialog(
	{
		title: title,
		close: function(){$dialog.dialog("destroy");},
		buttons: buttons,
		width: width,
		height: height
	}
	).show();
}

function showHTMLDialog(title, html, width, height) {
	jQuery("#imgDialog").html(html);
	var $dialog = jQuery("#imgDialog");
	
		var buttons = {"Close": function() {
			$dialog.dialog("destroy");}};
	
	$dialog.dialog(
	{
		title: title,
		close: function(){$dialog.dialog("destroy");},
		buttons: buttons,
		width: width,
		height: height
	}
	).show();
	
	
}


function setAutoCompleteContacts(sendToTextBoxId, widthInPx) 
{
		
		jQuery.get("/contacts/filter/all?q=", 
            function(data) {
			//alert(data);
                data = data.split("\n\r");
                jQuery("#"+sendToTextBoxId).autocomplete( data, {
                minChars:1,
                multiple: true,
                delay: 100,
                width: widthInPx + 'px',
				matchContains: true
                });
					 jQuery("#"+sendToTextBoxId).blur();
				 //jQuery("#"+sendToTextBoxId).focus();
            });
	
}


	function toggleMask(item, value, isClick) {
	
		if (jQuery(item).val() == value) {
				jQuery(item).attr("style", "color:black;");
				
				jQuery(item).val("");
				
				
			}
			else 
				if (jQuery(item).val() == "" && !isClick ) {
					jQuery(item).attr("style", "color:darkgray;");
					jQuery(item).val(value);
					
				
				}
		
		
		
	}

function setTimeZoneOnly(timeZoneId){
	var currentDate = new Date();
	jQuery("#"+ timeZoneId).val(currentDate.getTimezoneOffset().toString());
	
}

function setTimeZone(dateId, monthId, yearId, hrsId, minsId, timeZoneId){
	var currentDate = new Date();
	
	jQuery("#" + dateId).val(currentDate.getDate());
	jQuery("#" + monthId).val(currentDate.getMonth() + 1);
	if (yearId != null) {
		jQuery("#" + yearId).val(currentDate.getFullYear());
	}
	//jQuery("#schedule_recurs_until_3i").val(currentDate.getDate());
	//jQuery("#schedule_recurs_until_2i").val(currentDate.getMonth()+1);
	//jQuery("#schedule_recurs_until_1i").val(currentDate.getFullYear());
	var hrs;
	var mins;
	if (currentDate.getHours() < 10) {
		hrs = '0' + currentDate.getHours();
	}
	else {
		hrs = currentDate.getHours();
	}
	if (currentDate.getMinutes() < 10) {
		mins = '0' + currentDate.getMinutes();
	}
	else {
		mins = currentDate.getMinutes();
	}
	if (hrsId != null) {
	
	jQuery("#" + hrsId).val(hrs);
	jQuery("#" + minsId).val(mins);
	}
	jQuery("#"+ timeZoneId).val(currentDate.getTimezoneOffset().toString());
	//jQuery("#schedule_recurs_until_4i").val(hrs);
	//jQuery("#schedule_recurs_until_5i").val(mins);
	
}


function shareService(account_id, entity, callback) {

    jQuery("#share_entity").html(entity);
    new Users().load_shared_users("unshared_id", "unshared", entity, account_id);
    new Users().load_shared_users("shared_id", "shared", entity, account_id);

    showDialog('share_service', 'Share this ' + entity + ' with another user', 350, 650, {
        "Cancel": function() {
            jQuery(this).dialog("close");
            jQuery(this).dialog("destroy");
        },
        "Save": function() {
            confirm("Are you sure you would like to share this " + entity + " with the selected users?", function() {
                jQuery(this).dialog("close");
                jQuery(this).dialog("destroy");
                startProcess("Sharing " + entity + "s...");
                var userIDs = new Array();
                var userNames = new Array();
                jQuery("#shared_id :option").each(function(i, selected) {

                    userIDs.push(jQuery(selected).val());
                    userNames.push("<b>" + jQuery(selected).text() + "</b>");

                });
                if (callback != null) {
                    callback(userNames);
                }
                new Users().share_with_users(userIDs.join(","), entity, account_id);
                jQuery(this).dialog("close");
                jQuery(this).dialog("destroy");
                jQuery("#share_service").dialog("close");
                jQuery("#share_service").dialog("destroy");
            });




        } 
    });


}

function teamShareService() {

    /*jQuery("#share_entity").html(entity);
    new Users().load_shared_users("unshared_id", "unshared", entity, account_id);
    new Users().load_shared_users("shared_id", "shared", entity, account_id);
*/
    
    //load users first...
    //new Users().load_shared_users("bulk_share_user_id", "unshared", "service", null, null, function() {load_bulk_items();} );
    
    showDialog('bulkshare_service', 'Sharing', 480, 750, {
        "Close": function() {
            jQuery(this).dialog("close");
            jQuery(this).dialog("destroy");
        }
       
    });


}

function addSelected(from, to) {
    var totalAdded = 0;

    jQuery("#" + from + " :selected").each(function(i, selected) {

        jQuery("#" + to).append("<option  value=\"" + jQuery(selected).val() + "\">" + jQuery(selected).text() + "</option>");
        totalAdded++;
    });
    

}

function removeSelected(from) {
 var totalAdded = 0;
    jQuery("#" + from + " :selected").each(function(i, selected) {

        jQuery(selected).remove();
        totalAdded++;

    });



}

/*****
option -    callback (javascript code when menu item is clicked)
            title (title of menu item)
******/
function inlineMenu(options, id) 
{

    var result = "";
    result += "<span class=\"inlineMenuOptions\" style=\"float:right; height:0px;\">";
    result += "<span role=\"button\" class=\"a-j Mo bg\" title=\"Options menu\" tabindex=\"0\" aria-haspopup=\"true\" onclick=\"jQuery(this).next().toggle();\"></span>";
    result += "<div class=\"Om a-z\" style=\"-webkit-user-select: none; left: -5px; top: 20px; display: none;\" role=\"menu\" aria-haspopup=\"true\" tabindex=\"-1\" aria-activedescendant=\"\">";
    for (var i = 0; i < options.length; i++) {
        result += "<div class=\"c-G-j a-H c-G-j-Bc yo\" role=\"menuitem\" style=\"-webkit-user-select: none;  \" onclick=\"" + options[i].callback + " jQuery(this).parent().hide();\"><div class=\"a-H-r\" style=\"-webkit-user-select: none; cursor: pointer !important;font-weight:normal;\">" + options[i].title + "</div></div>";
    }
    result += "</div>";
    result += "</span>";

    jQuery('body').click(function(event) {
    if (!jQuery(event.target).closest('.inlineMenuOptions').length) {
        jQuery('.Om').hide();
        };
    });


    return result;

}

/*****
option -    callback (javascript code when menu item is clicked)
title (title of menu item)
******/
function inlineButton(title, options, id) {

    var result = "";
    result += "<div class=\"inlineMenuOptions G-Ni J-J5-Ji\"><div id=\":p4\" class=\"T-I J-J5-Ji ar7 T-I-ax7 L3 T-I-JW\" role=\"button\" tabindex=\"0\" aria-expanded=\"false\" style=\"-webkit-user-select: none; \" aria-haspopup=\"true\"  onclick=\"jQuery(this).find('.J-M').toggle();\">"
    result += "<span class=\"Ykrj7b\">"+title+"</span><div class=\"G-asx T-I-J3 J-J5-Ji\">&nbsp;</div>";
    
    result += "<div class=\"J-M jQjAxd\" style=\"-webkit-user-select: none; display: none; \" role=\"menu\" aria-haspopup=\"true\">";
    result += "<div class=\"SK AX\" style=\"-webkit-user-select: none; \">";
    for (var i = 0; i < options.length; i++) {
        result += "<div class=\"J-N\" selector=\"all\" role=\"menuitem\" style=\"-webkit-user-select: none; \" onclick=\"" + options[i].callback + " jQuery(this).parent().hide();\" id=\":ye\">";
        result += "<div class=\"J-N-Jz\" style=\"-webkit-user-select: none; \">" + options[i].title + "</div>";
        result += "</div>";
    }
    
    result+= "</div></div>";
    result += "</div></div>";
  
    jQuery('body').click(function (event) {
        if (!jQuery(event.target).closest('.inlineMenuOptions').length) {
            jQuery('.SK').hide();
        };
    });


    return result;

}
