var documentheight = 0;
$(document).ready(function() {
	if (!$('#main-nav li.b-dashboard a').hasClass('active')) {
		$('#subnav').hide();
	};
	$('#welcome .box .color-box').hide();
	tooltip();
	$('table tr:odd').addClass('odd-row');

	$('.toggle-table tbody tr[class^=for-]').hide();
	$('.toggle-table tbody tr.for-campaign-1').show();

	$('#write-ad-block').hide();
	
    $(document).ajaxError(function(e, xhr, settings, exception) {
        TopMessageAlert.showAlert('error in: ' + settings.url + ' \n'+'error:\n' + xhr.responseText);
    }); 

    shortcut.add("Ctrl+Shift+1",function() {
	    TopMessageAlert.enableAlert = !(TopMessageAlert.enableAlert);
    });
});
$(function() {
    documentheight = ($(document).height() - $("#footer").height()) - $("#header").height();
	$('.status-dropdown').hover(function() {
		$(this).addClass('status-dropdown-hover');
	}, function() {
		$(this).removeClass('status-dropdown-hover');
	});
	$('.status-dropdown li').mouseover(function() {
		$(this).addClass('hover');
	}).mouseout(function() {
		$(this).removeClass('hover');
	});

	$('.sort-buttons ul li.dropdown').hover(function() {
		$(this).find('.dd-content').slideDown('fast');
		$(this).find('a:eq(0)').addClass('hover');
	}, function() {
		$(this).find('.dd-content').slideUp('fast');
		$(this).find('a:eq(0)').removeClass('hover');
	});
	if ($('#how-pages').length) {
		$(window).scroll(function () {
			var top = $('#how-pages').position().top + $('#main').position().top + $('#how-pages h2:eq(0)').height();

			if ($.browser.safari) { var scollpos = document.body.scrollTop; } else { var scollpos = document.documentElement.scrollTop; }
			
			var sidebarheight = $('#how-pages #sidebar').height();
			
			if((parseInt(scollpos - top) + sidebarheight) <= documentheight) {
			    if (scollpos > top) { $('#how-pages #sidebar').css({'top' : parseInt(scollpos - top) + 'px'}); }
			}			
		});
	}

	$('.toggle-table tr.toggler').live('click', function() {
		$('.toggle-table tbody tr[class^=for-]').hide();
		$('.toggle-table tbody tr.toggler').removeClass('toggler-opened');
		$(this).addClass('toggler-opened');
		var id = $(this).attr('id');
		$(this).parents('.toggle-table tbody').find('tr.for-'+id).show();
	});
	
    $('#filters .toggler').click(function () {
	    if ($(this).parents('#filters:eq(0)').find('.content').is(':hidden')) {
		    //$(this).parents('#filters:eq(0)').find('.content').css("display") == "none"
		    $(this).parents('#filters:eq(0)').find('.content').slideDown();
            if($(this).html() == "Hide Answer")
                $(this).html('View Answer');
            else if($(this).html() == "Reply")
                $(this).html('Hide');
	        else
	            $(this).html('Hide Filters');		    
	    } else {
		    $(this).parents('#filters:eq(0)').find('.content').slideUp();
            if($(this).html() == "View Answer")
                $(this).html('Hide Answer');
            else if($(this).html() == "Hide")
                $(this).html('Reply');
            else
                $(this).html('Show Filters');		    
	    }
    });

	$('table tr').live('mouseover',function() {
		$(this).addClass('tr-hover');
	}).live('mouseout',function() {
		$(this).removeClass('tr-hover');
	});
	
	$('.all-expander').live('click', function() {
		$('.content-toggler').addClass('content-toggler-opened');
		$('.content-toggled').slideDown();
		$('.all-collapser').show();
		$('.all-expander').hide();
	});
	$('.all-collapser').live('click', function() {
		$('.content-toggler').removeClass('content-toggler-opened');
		$('.content-toggled').slideUp();
		$('.all-expander').show();
		$('.all-collapser').hide();
	});
	$('.content-toggler').live('click', function() {
		$(this).toggleClass('content-toggler-opened');
		$(this).next('.content-toggled').toggle('slow');
	});	
	
	$('#agency-box .menu').click(function() {
	    $(this).find('.expanding-content').eq(0).toggle();
	    return false;
    });
    $('#agency-box .menu').hover(
    	function () {},
    	function() { $(this).find('.expanding-content').eq(0).hide() }
	);
    $('#welcome .box').hover(
    	function() {
    		$(this).find('.color-box').eq(0).show();
    	},
    	function() {
    		$(this).find('.color-box').eq(0).hide();
    	});
	$('#welcome .close').click(function() {
		$('#welcome').slideUp();		
		return false;
	});
	$('input.field').
    focus(function() {
        if(this.title==this.value) {
            this.value = '';
        }
    }).
    blur(function(){
        if(this.value=='') {
            this.value = this.title;
        }
    });
    if ($.browser.msie && parseInt($.browser.version)==6) {
	    $('.hideselect').hover(function () {
	        $(this).next().css('visibility', 'hidden');
	    }, function () {
	        $(this).next().css('visibility', 'visible');
	    });
	}

	$('.challenge-box .side .ico, .health-info, .challenge-box .percent-box .ico').hover(function() {
		$(this).find('.bubble:eq(0)').show();
	}, function() {
		$(this).find('.bubble:eq(0)').hide();
	});
	
	$('.fbchallenge-box .side .ico, .health-info, .fbchallenge-box .percent-box .ico').hover(function() {
		$(this).find('.bubble:eq(0)').show();
	}, function() {
		$(this).find('.bubble:eq(0)').hide();
	});

	$('.bubble .close').live('click', function() {
		$(this).parents('.bubble:eq(0)').fadeOut();
	});	

	$('#write-ad-block .close, #write-ad-block .buttons a:contains(Cancel)').live('click', function() {
		$(this).parents('#write-ad-block:eq(0)').slideUp();
		$('.button-write-ad').removeClass('button-write-ad-active');
	});
	
	$('.button-write-ad').live('click', function() {
		$('#write-ad-block').slideDown();
		$(this).toggleClass('button-write-ad-active');
		return false;
	});
	
    $("input").each(function() {
        if($(this).attr("infotext") != undefined && $(this).attr("infotext") != "" && $(this).attr("type") != "password") {
            $(this).focus(function() {
                if($(this).attr("infotext") == $(this).val()) {
                    $(this).val("");
                    $(this).removeClass("infotext");
                }
            });

            $(this).blur(function() {
                if($(this).attr("infotext") != $(this).val() && $(this).val() == "") {
                    $(this).val($(this).attr("infotext"));
                    $(this).addClass("infotext");
                }
            });
        }
    });

	$('.yellowmessage-box .close').click(function() {
		$(this).parent().slideUp();
		return false;
	});

    AdWordsFunction.formatHeadline();
});


this.tooltip = function() {
    /* CONFIG */
    var xOffset = 20;
    var yOffset = -195;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result		
    /* END CONFIG */
    $("a.tooltip").hover(function(e) {
        width = "154";
        _yOffset = yOffset;
        this.t = this.title;
        if(this.title != "")
            $(this).attr("tiptext", this.title);
        this.title = "";

        if ($(this).attr("width") != undefined) {
            customWidth = $(this).attr("width");
            if (customWidth > width)
                _yOffset = _yOffset - (customWidth - width);
            else
                _yOffset = _yOffset + (width - customWidth);

            width = customWidth;
        }

        $("body").append("<div id='tooltip'><a href='#' class='close'>x</a><span class='arrow'>&nbsp;</span>" + this.t + "</div>");

        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + _yOffset) + "px")
			.css("width", width + "px")
			.fadeIn("fast");

    },
	function() {
	    if(this.t == null || this.t == undefined || this.t == "")
	    {
	        if($(this).attr("tiptext") != undefined && $(this).attr("tiptext") != "")
	            this.title = $(this).attr("tiptext");
	        else 
	            this.title = this.t;
	    } else {
	        this.title = this.t;
	    }
	    $("#tooltip").remove();
	});

	$("a.tooltip").mouseout(function(e) {
	    $("#tooltip").remove();
    });
	
	$("a.tooltip").mousemove(function(e) {
	    width = "154";
	    _yOffset = yOffset;
	    if ($(this).attr("width") != undefined) {
	        customWidth = $(this).attr("width");
	        if (customWidth > width)
	            _yOffset = _yOffset - (customWidth - width);
	        else
	            _yOffset = _yOffset + (width - customWidth);
	    }
	    
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + _yOffset) + "px");
    });

};

this.rowtooltip = function() {
    /* CONFIG */
    var xOffset = 20;
    var yOffset = 20;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result		
    /* END CONFIG */
    $("tr.rowtooltip td").each(function() {
        $(this).hover(function(e) {

        width = "154";
        _yOffset = yOffset;
        this.t = $(this).parent().attr("desc");
        
        if ($(this).parent().attr("width") != undefined) {
            customWidth = $(this).parent().attr("width");
            if (customWidth > width)
                _yOffset = _yOffset - (customWidth - width);
            else
                _yOffset = _yOffset + (width - customWidth);

            width = customWidth;
        }

        $("body").append("<div id='rowtooltip'><span class='arrow'>&nbsp;</span>" + this.t + "</div>");

        $("#rowtooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + _yOffset) + "px")
			.css("width", width + "px")
			.fadeIn("fast");        
        },
	    function() {
            $("#rowtooltip").remove();
	    })
	});
	$("tr.rowtooltip").mousemove(function(e) {
        width = "154";
        _yOffset = yOffset;
        if ($(this).attr("width") != undefined) {
            customWidth = $(this).attr("width");
            if (customWidth > width)
                _yOffset = _yOffset - (customWidth - width);
            else
                _yOffset = _yOffset + (width - customWidth);
        }

        $("#rowtooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + _yOffset) + "px");
    });

};


var HTMLCode = {
    Encode: function(obj) {
        return obj.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    },
    Decode: function(obj) {
        return html.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
    }
}
var FiledValidation = {
    IsValidEmail: function(obj) {
         var fieldvalue = $(obj).val();
         fieldvalue = $.trim(fieldvalue);
         if(fieldvalue.toLowerCase().indexOf("@test.com") > 0)
            return false;
         if (fieldvalue.length >0) {
             i=fieldvalue.indexOf("@");
             j=fieldvalue.indexOf(".",i);
             k=fieldvalue.indexOf(",");
             kk=fieldvalue.indexOf(" ");
             jj=fieldvalue.lastIndexOf(".")+1;
             len=fieldvalue.length;
            if ((i>0) && (j>(1+1)) && (k==-1) && (kk==-1) && (len-jj >=2) && (len-jj<=3)) {
            }
            else {
                return false;
            }
            return true;
         }
    },
    IsNoSpecialChar: function(obj) {
        var fieldvalue = $(obj).val();
        var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

        for (var i = 0; i < fieldvalue.length; i++) {
            if (iChars.indexOf(fieldvalue.charAt(i)) != -1) {
                return false;
            }
        }
        return true;
    },
    IsChar: function(obj) {
        var fieldvalue = $(obj).val();
        var noalpha = /^[a-zA-Z]*$/;
        if (noalpha.test(fieldvalue))
            return true;
        else
            return false;
    },
    IsPhoneNumber: function(obj) {
        var fieldvalue = $(obj).val();
        //var nonums = /^[0-9]*-[0-9]*-[0-9]*$/;
        var nonums = /^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;
        var nonums1 = /^((\((\d{3})\)|(\d{3}))\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;
        if (nonums.test(fieldvalue) || nonums1.test(fieldvalue))
             return true;
        else
             return false;
    },
    IsWebURL: function(obj) {
        var fieldvalue = $(obj).val();
        //var nonums = /^(((ht|f){1}(tp:[/][/]){1})|((www.){1}))[-a-zA-Z0-9@:%_\+.~#?&//=]+$/;
        var nonums = /^(((ht|f){1}(tp:[/][/]){1})|((ht|f){1}(tps:[/][/]){1}))[-a-zA-Z0-9@:%_\+.~#?&//=]+$/;
        if (nonums.test(fieldvalue))
             return true;
        else
             return false;
    },
    GetUpperWordCount: function(str, limit, ignorewords) {
        var UpperChars = "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".split(' ');
        var upperWordCount = 0;
        var IsLastUpper = false;
        var subCount = 0;
        var lastWord = "";
        if(limit == undefined)
            limit = 3;
        if(ignorewords == undefined)
            ignorewords = "";
        else
            ignorewords = ' ' + ignorewords.split(',').join(' ') + ' ';
        str = str + ' ';
        str = str.split('');
        for (var i=0; i < str.length; i++)
        {
	        IsLastUpper = false;
	        var lastchar = "";
	        for(var c=0; c <= UpperChars.length; c++)
	        {
	           if (str[i] == UpperChars[c]) {
	                IsLastUpper = true;
	                lastchar = str[i];
	           }
	        }
	        if(IsLastUpper) {
	            subCount++;
	            lastWord += lastchar;
	            if(subCount >= limit) {
                    if(ignorewords.indexOf(' ' + lastWord) < 0) {
                        upperWordCount++;
                    }
                }
	        }
	        else {
                if(subCount >= limit && ignorewords.indexOf(' ' + lastWord + ' ') < 0) {
                    upperWordCount++;
                }
                subCount = 0;
                lastWord = "";
	        }
        }
        return upperWordCount;
    }
};

var FBCommon = {
    getAdBlock: function(destinationurl, headline, body, imageurl, imageheight, imagewidth, healineid, bodyid) {
        var sb = "";
        try {
            sb += "<div class='boostab leftalign' style='height:120px; width:268px;'>";
            sb += "<div><a " + (healineid != null ? "id='" + healineid + "'" : "") + " class='fbheadline' target='_blank' style='text-decoration:none;' href='" + destinationurl + "'>" + headline + "</a></div>";
            sb += "<div align='left' style='height:90px; width:120px; float:left; position:relative; padding-top:5px;' class='adimagethumb'>";
            if(imageurl != null && imageurl != "") {
                sb += "<a href='javascript:' id='A4' style='display:inline;'>";
                sb += "<img src='" + imageurl + "' height='" + (imageheight > 0 ? imageheight : 90) + "' width='" + (imagewidth > 0 ? imagewidth : 120) + "' style='display:inline;' />";
                sb += "</a>";
            } else {
                sb += "<img src='/Content/images/not_available.gif' alt='' style='display:inline;' class='blackborder' height='80' width='120' />";
            }
            sb += "</div>";
            sb += "<div align='left' style='height:90px; width:135px; padding:5px; float:right; position:relative; overflow:hidden;'>";
            sb += "<div class='adline1' " + (bodyid != null ? "id='" + bodyid + "'" : "") + " style='font-size:8pt;'>" + body + "</div>";
            sb += "</div>";
            sb += "</div>";
        } catch(e) { sb = e; }
        return sb;
    }
}

var CustomAdCommon = {
    getAdBlock: function(destinationurl, headline, Line1, Line2, imageurl, imageheight, imagewidth, healineid, idLine1, idLine2) {
        var sb = "";
        try {
            sb += "<div class='boostab leftalign' style='height:120px; width:268px;'>";
            sb += "<div><a " + (healineid != null ? "id='" + healineid + "'" : "") + " class='customadheadline' target='_blank' style='text-decoration:none;' href='" + destinationurl + "'>" + headline + "</a></div>";
            sb += "<div align='left' style='height:90px; width:120px; float:left; position:relative; padding-top:5px;' class='adimagethumb'>";
            if(imageurl != null && imageurl != "") {
                sb += "<a href='javascript:' id='A4' style='display:inline;'>";
                sb += "<img src='" + imageurl + "' height='" + (imageheight > 0 ? imageheight : 90) + "' width='" + (imagewidth > 0 ? imagewidth : 120) + "' style='display:inline;' />";
                sb += "</a>";
            } else {
                sb += "<img src='/Content/images/not_available.gif' alt='' style='display:inline;' class='blackborder' height='80' width='120' />";
            }
            sb += "</div>";
            sb += "<div align='left' style='height:90px; width:135px; padding:5px; float:right; position:relative; overflow:hidden;'>";
            sb += "<div class='adline1' " + (idLine1 != null ? "id='" + idLine1 + "'" : "") + " style='font-size:8pt;'>" + Line1 + "</div>";
            sb += "<div class='adline2' " + (idLine2 != null ? "id='" + idLine2 + "'" : "") + " style='font-size:8pt;'>" + Line2 + "</div>";
            sb += "<div style='font-size:8pt;'>" + destinationurl + "</div>";
            sb += "</div>";
            sb += "</div>";
        } catch(e) { sb = e; }
        return sb;
    }
}

var ProcessOverlay = {
    show: function(parentDivID, displayMessage) {
        if(displayMessage == undefined)
            displayMessage = "";
        if($("#" + parentDivID).length == 0)
            return;
        var offsetWidth = $("#" + parentDivID).width();
        var offsetHeight = $("#" + parentDivID).height();
        
        var leftPadding = $("#" + parentDivID).css("padding-left").replace('px','');
        var rightPadding = $("#" + parentDivID).css("padding-right").replace('px','');
        var topPadding = $("#" + parentDivID).css("padding-top").replace('px','');
        var bottomPadding = $("#" + parentDivID).css("padding-bottom").replace('px','');
        
        if(parseInt(topPadding) > 0)
            offsetHeight = (offsetHeight + parseInt(topPadding));
        //if(parseInt(bottomPadding) > 0)
        //    offsetHeight = (offsetHeight + parseInt(bottomPadding));
        
        if(parseInt(leftPadding) > 0)
            offsetWidth = (offsetWidth + parseInt(leftPadding));
        //if(parseInt(rightPadding) > 0)
        //    offsetWidth = (offsetWidth + parseInt(rightPadding));
        
        $("#" + parentDivID).addClass("ajaxContainer");
        
        var loadingImage = "/content/images/ajax-loader.gif";
        var top = parseInt((offsetHeight - 100) / 2);
        var left = parseInt((offsetWidth - 100) / 2);
        
        var inlineStyle = "";
        if(offsetWidth < 300 || offsetHeight < 300) {
            loadingImage = "/content/images/loading_animation2.gif";
            top = parseInt((offsetHeight - 32) / 2);
            left = parseInt((offsetWidth - 32) / 2);
            inlineStyle = "display:inline;";
        }        
        
        var strOverlay = "<div id='" + parentDivID + "Ajax' class='ajaxMainProcessing' style='height:" + offsetHeight + "px; width:" + offsetWidth + "px; top:0px; left:0px;'>";
        strOverlay += "<div class='ajaxProcessing' style='padding:5px; background-color: #C6C6C6; height:" + (offsetHeight - 10) + "px; width:" + (offsetWidth - 10) + "px;'>";
        strOverlay += "<img id='ajaxbg' src='/content/images/grey1px.png' />";
        strOverlay += "</div>";
        strOverlay += "<img id='ajaximage' class='ajaxProcessingimg' src='" + loadingImage + "' style='" + inlineStyle + "top:" + top + "px; left:" + left + "px;' />";
        if(displayMessage != "")
            strOverlay += "<div id='ajaxMessage' style='" + inlineStyle + "top:" + (top + 100) + "px;' align='center' class='ajaxMessage'>" + displayMessage + "</div>";
        strOverlay += "</div>";
        
        $("#" + parentDivID).append(strOverlay);
    },
    
    updateMessage: function(parentDivID, displayMessage) {
        $("#" + parentDivID + "Ajax #ajaxMessage").html(displayMessage);
    },
    
    hide: function(parentDivID) {
        $("#" + parentDivID + "Ajax").remove();
    },
    
    refresh: function(parentDivID) {
        ProcessOverlay.hide(parentDivID);
        ProcessOverlay.show(parentDivID);
    },

    delayRefresh: function(parentDivID, delay) {
        if(delay == undefined)
            delay = 100;
        setTimeout("ProcessOverlay.hide('" + parentDivID + "'); ", delay);
        setTimeout("ProcessOverlay.show('" + parentDivID + "'); ", (delay + 100));
    },
    
    showFullProgress: function() {
        if($("#pnlBackground").length == 0) {
            var fullOverlay = '<div id="pnlBackground" style="display:none;position:absolute;-moz-opacity:0.8;opacity:0.8; filter: alpha(opacity=80); BACKGROUND-COLOR: #000;top:0px;left:0px;bottom:0px;right:0px; margin-bottom:0px;width:100%;height:1200px;" align="center" />';
            fullOverlay += '<div id="pnlForeground" style="display:none;position:absolute;top:0px;left:0px;width:100%;height: 1200px;">';
            fullOverlay += '<table style="margin-left: 25%; margin-right: 25%; margin-bottom: 0%; width: 50%;">';
            fullOverlay += '<tr><td align="left" style="position: absolute; top: 80px;display:none;">';
            fullOverlay += '<label id="lblProgressOpt" style="font-weight:bold;font-size:14px;color:White;"></label>';
            fullOverlay += '<img id="imgProgressOpt" src="/content/images/loading_animation1.gif" alt="" />';
            fullOverlay += '</td></tr><tr><td align="center"><img id="imgProgressBtn" src="/content/images/loading_animation5.gif" alt="" /></td></tr>';
            fullOverlay += '<tr><td align="center" style="height:70px;">';
            fullOverlay += '<label id="lblProgressBtn" style="font-weight:bold;font-size:20px;color:White;">Setting up your contests...</label>';
            fullOverlay += '<br /><br /><br /><label id="lblSetupProgress" style="font-weight:bold;font-size:20px;color:White;">Your Request in Progress</label>';
            fullOverlay += '</td></tr><tr><td align="center"><table style="background-color: transparent;" ID="tblBenefits" width="100%">';
            fullOverlay += '<tr style="height: 30px;"><td colspan="5"></td></tr><tr><td style="width: 3%;">&nbsp;</td>';
            fullOverlay += '<td colspan="3" align="left" style="height:35px;"><label id="lblBenefits" style="font-weight:bold;font-size:24px;color:#FFA500;"></label></td>';
            fullOverlay += '<td style="width: 3%;">&nbsp;</td></tr><tr><td style="width: 30%;"></td><td style="width: 4%;">&nbsp;</td>';
            fullOverlay += '<td style="width: 70%;height:30px;" align="left"><label id="lblMetrics" style="font-weight:bold;font-size:20px;color:#ADD8E6;"></label>';
            fullOverlay += '</td></tr><tr><td style="color: #f5f5f5;" align="left" colspan="3"><label id="lblDescription" style="color:#FFFFFF;font-weight:bold;font-size:12pt;line-height:30px;">';
            fullOverlay += '<font style="color:Yellow">A note on timing:</font> We are retrieving a list of your ad groups.  If you have over 100 ad groups, this could take several minutes.'
            fullOverlay += '</label></td></tr><tr><td>&nbsp;</td></tr></table></td></tr></table></div>';
            $("body").append(fullOverlay);
        }
        $('#pnlBackground').show();
        $('#pnlForeground').show();
        $('#lblProgressOpt').show();
        $('#lblProgressBtn').show();
        $('#imgProgressOpt').show();
        $('#imgProgressBtn').show();        
    },
    hideFullProgress: function() {
        $('#pnlBackground').hide();
        $('#pnlForeground').hide();
        $('#lblProgressOpt').hide();
        $('#lblProgressBtn').hide();
        $('#imgProgressOpt').hide();
        $('#imgProgressBtn').hide();
    }
}


function isValidDate(controlName) {
    var isValid = true;
    var val = $('#' + controlName).val();
    var regexp = /^\d{1,2}\/\d{1,2}\/\d{4}$/;

    if (!regexp.test(val)) {
        isValid = false;
    };
    return isValid;
}

function CompareGreaterDate(StartDate,EndDate) {
    if(!isValidDate(StartDate))
        return false;

    if(!isValidDate(EndDate))
        return false;
        
    try {
        var startdate = new Date($("#" + StartDate).val());
        var enddate = new Date($("#" + EndDate).val());
        if(enddate < startdate)
            return false;
        else
            return true;
    } catch(e) {
        alert(e);
        return false;
    }
    return true;
}

function formatToComma(nStr) {
    nStr += '';
    nStr = $.trim(nStr);
    nStr = (nStr == "" ? "0" : nStr);
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

var CustomMessagebox = {
    MessageBody: '',
    MessageTitle: '',
    BoxHeight: 250,
    BoxWidth: 500,
    showMessage: function(Title, Message, Height, Width) {
        if(Message.indexOf("\n") > 0)
            Message = Message.split("\n").join("<br/>");
        this.MessageBody = Message;

        $("#MessageBody").html(Message);

        if(Title.indexOf("\n") > 0)
            Title = Title.split("\n").join("<br/>");
        this.MessageTitle = Title;
        $("#lblMessageTitle").html(Title);
        
        if(Height != null && Width != null)
        {
            if(Height > 0)
                this.BoxHeight = Height;
            if(Width > 0)
                this.BoxWidth = Width;
            setTimeout("CustomMessagebox.doreSize(" + this.BoxHeight + "," + this.BoxWidth + ");", 800);
        }
    },
    doreSize: function(Height, Width) {
        var leftMargin = 0;
        try {
            var left = (parseInt(Width) / 2);
            $("#TB_window").css("margin-left", "-" + left + "px");
            var top = (parseInt(Height) / 2);
            $("#TB_window").css("margin-top", "-" + top + "px");
        } catch (e) { }

        $("#TB_window").css("width", parseInt(Width) + "px");
        $("#TB_ajaxContent").css("width", (parseInt(Width) - 30) + "px");
        $("#TB_ajaxContent").css("height", parseInt(Height) + "px");
    }    
}

var TopMessageAlert = {
   enableAlert: false,
   showAlert: function(message, alertType, cssClass) {
       if(this.enableAlert == false)
            return;
            
       if(alertType == undefined)
            alertType = "top";
       
       switch(alertType) {
            case "top":
                if($("#topAlert").length == 0) {
                    $("body").append("<div id='topAlert' align='center'><div " + (cssClass != undefined ? " class='message " + cssClass + "'" : " class='message'") + ">" + message + "</div></div>");
                    setTimeout("$('#topAlert').remove();", 5000);
                }
                break;
            case "window":
                alert(message);
                break;
       }
   }
}

shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target;
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code).toLowerCase();
			
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown

			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
			
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}

function ExpandFindMore() {
    if ($("#trfindmore").css("display") == "none")
        $("#trfindmore").css("display", "block");
    else
        $("#trfindmore").css("display", "none");
}

var AdWordsFunction = {
    getHeadlineLength: function(textid, excludeKeyword) {
        if(excludeKeyword == undefined || excludeKeyword == null)
            excludeKeyword = false;
        var strVal = $("#" + textid).val();
        if (!excludeKeyword && strVal.toLowerCase().indexOf("{keyword:") >= 0) {
            if (strVal.indexOf("}") > strVal.toLowerCase().indexOf("{keyword:")) {
                $("#" + textid).attr("maxlength", 35);
                strVal = strVal.substring(0, strVal.toLowerCase().indexOf("{keyword:")) + strVal.substring(strVal.toLowerCase().indexOf("{keyword:") + 9, strVal.indexOf("}")) + strVal.substring(strVal.indexOf("}") + 1, strVal.length);
                return (25 - parseInt(strVal.length));
            } else {
                var cnt = 25 - parseInt(strVal.length);
                return cnt;
            }
        }
        else {
            if (strVal.length > 25) {
                $("#" + textid).val(strVal.substring(0, 25));
            }
            $("#" + textid).attr("maxlength", 25);
            var cnt = 25 - parseInt(strVal.length);
            return cnt;
        }
    },
    
    getLine1Length: function(textid, excludeKeyword) {
        if(excludeKeyword == undefined || excludeKeyword == null)
            excludeKeyword = false;    
        var strVal = $("#" + textid).val();
        if (!excludeKeyword && strVal.toLowerCase().indexOf("{keyword:") >= 0) {
            if (strVal.indexOf("}") > strVal.toLowerCase().indexOf("{keyword:")) {
                $("#" + textid).attr("maxlength", 45);
                strVal = strVal.substring(0, strVal.toLowerCase().indexOf("{keyword:")) + strVal.substring(strVal.toLowerCase().indexOf("{keyword:") + 9, strVal.indexOf("}")) + strVal.substring(strVal.indexOf("}") + 1, strVal.length);
                return (35 - parseInt(strVal.length));
            } else {
                var cnt = 35 - parseInt(strVal.length);
                return cnt;
            }
        }
        else {
            if (strVal.length > 35) {
                $("#" + textid).val(strVal.substring(0, 35));
            }
            $("#" + textid).attr("maxlength", 35);
            var cnt = 35 - parseInt(strVal.length);
            return cnt;
        }
    },
    
    getLine2Length: function(textid, excludeKeyword) {
        if(excludeKeyword == undefined || excludeKeyword == null)
            excludeKeyword = false;    
        var strVal = $("#" + textid).val();
        if (!excludeKeyword && strVal.toLowerCase().indexOf("{keyword:") >= 0) {
            if (strVal.indexOf("}") > strVal.toLowerCase().indexOf("{keyword:")) {
                $("#" + textid).attr("maxlength", 45);
                strVal = strVal.substring(0, strVal.toLowerCase().indexOf("{keyword:")) + strVal.substring(strVal.toLowerCase().indexOf("{keyword:") + 9, strVal.indexOf("}")) + strVal.substring(strVal.indexOf("}") + 1, strVal.length);
                return (35 - parseInt(strVal.length));
            } else {
                var cnt = 35 - parseInt(strVal.length);
                return cnt;
            }
        }
        else {
            if (strVal.length > 35) {
                $("#" + textid).val(strVal.substring(0, 35));
            }
            $("#" + textid).attr("maxlength", 35);
            var cnt = 35 - parseInt(strVal.length);
            return cnt;
        }    
    },

    getKeywordfilter: function(strVal) {
        if (strVal == undefined) return "";
        if (strVal.toLowerCase().indexOf("{keyword:") >= 0) {
            if (strVal.indexOf("}") > strVal.toLowerCase().indexOf("{keyword:")) {
                strVal = strVal.substring(0, strVal.toLowerCase().indexOf("{keyword:")) + strVal.substring(strVal.toLowerCase().indexOf("{keyword:") + 9, strVal.indexOf("}")) + strVal.substring(strVal.indexOf("}") + 1, strVal.length);
                return strVal;
            }
        }
        return strVal;
    },
    
    formatHeadline: function() {
        $(".boostab .headline,.boostab .main,.boostab .adheadline").each(function() {
            var headline = $(this).html();
            if(headline.toLowerCase().indexOf("{keyword:") >= 0) {
                if(headline.length >= 30)
                    $(this).css("font-size","13px");
                else if(headline.length >= 24)
                    $(this).css("font-size","14px");
                else if(headline.length >= 18)
                    $(this).css("font-size","15px");
            }
        });        
    }
}
var AdCenterFunction = {
    getLine1Length: function(textid, excludeKeyword) {
        if (excludeKeyword == undefined || excludeKeyword == null)
            excludeKeyword = false;
        var strVal = $("#" + textid).val();
        if (!excludeKeyword && strVal.toLowerCase().indexOf("{keyword:") >= 0) {
            if (strVal.indexOf("}") > strVal.toLowerCase().indexOf("{keyword:")) {
                $("#" + textid).attr("maxlength", 80);
                strVal = strVal.substring(0, strVal.toLowerCase().indexOf("{keyword:")) + strVal.substring(strVal.toLowerCase().indexOf("{keyword:") + 9, strVal.indexOf("}")) + strVal.substring(strVal.indexOf("}") + 1, strVal.length);
                return (70 - parseInt(strVal.length));
            } else {
                var cnt = 70 - parseInt(strVal.length);
                return cnt;
            }
        }
        else {
            if (strVal.length > 70) {
                $("#" + textid).val(strVal.substring(0, 70));
            }
            $("#" + textid).attr("maxlength", 70);
            var cnt = 70 - parseInt(strVal.length);
            return cnt;
        }
    }
}

// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function() {
    return this.each(function() {
        $(this).keydown(function(e) {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

function encodeHTML(str) {
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}
