// for getting the top left coordinate of elem in relation to the page
function getTopLeft(elm) {

        var x, y = 0;

    //set x to elm’s offsetLeft
    x = elm.offsetLeft;

    //set y to elm’s offsetTop
y = elm.offsetTop;

    //set elm to its offsetParent
    elm = elm.offsetParent;

    //use while loop to check if elm is null
    // if not then add current elm’s offsetLeft to x
    //offsetTop to y and set elm to its offsetParent

    while(elm != null)
     {

        x = parseInt(x) + parseInt(elm.offsetLeft);
        y = parseInt(y) + parseInt(elm.offsetTop);
        elm = elm.offsetParent;
     }

    //here is interesting thing
    //it return Object with two properties
    //Top and Left

    return {Top:y, Left: x};
}
function getTimeStamp() {
	var date = new Date();
	var timestamp = date.getTime();
	return timestamp;
}
function fixDialogLook() {
//    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
//        $("body").append("<iframe class='TB_HideSelect'></iframe>");
//    }
}
function isChecked(cbName) {
    if (document.getElementById(cbName) == null) return false;
    if (document.getElementById(cbName).checked) return true;
    else return false;
}
// buggy...not used
function convertToLinks2(text) {
    var strArr = text.split(' ');
    var result = '';
    for (var i = 0; i < strArr.length; i++) {
        if (strArr[i].substring(0,7) == "http://")
            strArr[i] = '<a href="' + strArr[i] + '">' + strArr[i]  + '</a>';
        result += strArr[i];
    }
    return result;
}
// need a better regex so won't need http:// in front
function convertToLinks(x)
{
  function convert(str, p1, offset, s)
  {
    return '<a href="' + p1 + '" target="_blank">' + p1 + '</a>';
  }
  var s = String(x);

//var test = /^(((ht|f)tp(s?))\:\/\/)?(([a-z0-9.-]|%[0-9A-F]{2}){3,})(?::(\d+))?((?:\/(?:[a-z0-9-._~!$&'()*+,;=:@]|%[0-9A-F]{2})*)*)(?:\?((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9A-F]{2})*))?(?:#((?:[a-z0-9-._~!$&'()*+,;=:\/?@]|%[0-9A-F]{2})*))?$/i;

//var test = /^(((ht|f)tp(s?))\:\/\/)?((([a-zA-Z0-9_\-]{2,}\.)+[a-zA-Z]{2,})|((?:(?:25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)(?(\.?\d)\.)){4}))(:[a-zA-Z0-9]+)?(\/[a-z0-9-._~!$&'()*+,;=:\/?@#]*)?$/i;
    var test = /((\s?)(mailto\:|(news|(ht|f)tp(s?))\:\/\/){1}\S+)/gi;
//    var test = /(abcd)/gi;
  return s.replace(test, convert);

}

function isEmail(email) {
    return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(email);
}
function convertHtmlTags(s) {
    if (!s || s == null || s == '') return '';
    s=s.replace(/&/g,'&amp;');
    s=s.replace(/</g,'&lt;');
    s=s.replace(/>/g,'&gt;');
//    s=s.replace(/\n/g,'<br />\n');
    s=s.replace(/\r/g,'');
    return s;
}
// this function determines whether the event is the equivalent of the microsoft
// mouseleave or mouseenter events.
function isMouseLeaveOrEnter(e, handler)
{
    try {
        var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
        while (reltg && reltg != handler) reltg = reltg.parentNode;
        return (reltg != handler);
    } catch (e) {
        return false;
    }
}
function checkPassword(whatYouTyped) {
    var fieldset = whatYouTyped.parentNode;
    var txt = whatYouTyped.value;
    if (txt.length >= 6) {
        fieldset.className = "welldone";
    } else {
        fieldset.className = "";
    }
}

function checkEmail(whatYouTyped) {
	var fieldset = whatYouTyped.parentNode;
	var txt = whatYouTyped.value;
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt)) {
		fieldset.className = "welldone";
	} else {
		fieldset.className = "";
	}
}

function checkNotEmpty(obj){
            if($(obj).val()!=''){
                 $(obj).parent().addClass('welldone');
            }
           else{
                $(obj).parent().removeClass('welldone');
            }
        }

function escapeSingleQuotes(msg){
    return msg.split("'").join("\\'") ;
}
// enforce maxlength for textarea
function enforceMaxLength(inputElem, maxLength) {
    if ($(inputElem).val().length >= maxLength) $(inputElem).val($(inputElem).val().substring(0, maxLength));
}
function inList(list, value) {
    for (var i = 0; i < list.length; i++) {
        if (value == list[i]) return true;
    }
    return false;
}
function checkBlockElem(cbElem, elemToBlock) {
    if (cbElem.checked) {
        $('#' + elemToBlock).block({ message: null });
    }
    else {
        $('#' + elemToBlock).unblock();
    }
}
function extractFileName(what) {
    var answer;
    if (what.indexOf('/') > -1)
        answer = what.substring(what.lastIndexOf('/')+1,what.length);
    else
        answer = what.substring(what.lastIndexOf('\\')+1,what.length);
    return answer;
}
function isValidFileType(what) {
    var ext = what.substring(what.lastIndexOf('.')+1,what.length).toLowerCase();
    return !(ext == 'exe' || ext == 'dll' || ext == 'ocx' || ext == 'com' || ext == 'bat');
}
function dialogWindowClosed(obj, data) {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
        $('#TB_HideSelect').trigger("unload").unbind().remove();
    }
    $('.ui-dialog-buttonpane').unblock();
}

// feedback pop up; moved to mmCommon.js from mm.js because help page needs access
function setupFeedbackWindow() {
    $.post(loadFeedbackDlgUrl, function(data) {
        $('body').append(data);
        var options = {
//            autoOpen:false,
            height:300,
            width:610,
            modal:true,
            overlay:{opacity: 0.5,background: "black"},
            minHeight:250,
            minWidth:200,
            open: fixDialogLook,
            close:clearFeedbackForm,
            resize:taskWindowResize,
            bgiframe:true,
            buttons:{
                "Close":function() {
    //                $('#feedback').val('');
                    $(this).dialog("close");
                }
                /*
                "Submit":function() {
                    showDialogButtonPaneMsg('Please wait...');
                    var params = $("#feedbackForm");
                    var dlg = $(this);
                    $.ajax({
                        url:leaveFeedbackURL,
                        data:params.serialize(),
                        success:function(data) {
                            if (data == 'Thank You') {
                                $('#feedback').val('');
                                alert('Your feedback has been successfully sent.');
                                dlg.dialog("close");
                            }
                            else {
                                showRemoteMessage('feedbackMessageDiv',data);
                            }
                        }
                    });
                }
                */
            }
        };
        $('#feedbackDiv').dialog(options);
    });
}
function clearFeedbackForm() {
    $('#feedback').val('');
    dialogWindowClosed();
}
function loadFeedbackWindow() {
    if ($('#feedbackDiv').size() == 0) setupFeedbackWindow();
    else {
        $('#feedbackDiv').dialog('open');
        $('#feedback').focus();
    }
}
// end feedback section
function showDialogButtonPaneMsg(msg, dlgDiv) {
    $('.ui-dialog-buttonpane').unblock();
    var target = dlgDiv ? $(dlgDiv).parent().find('.ui-dialog-buttonpane') : $('.ui-dialog-buttonpane');
    $(target).block({ message: msg, css: {color: 'black'}, overlayCSS: { backgroundColor: 'yellow'} });
}
function setInputHint(inputElem) {
    $(":text").labelify({labelledClass: "labelHighlight"});
}
function selectAllCb(cb, formName) {
//    alert($(cb).attr('checked'));
    if ($(cb).attr('checked')) {
        $('#' + formName + ' input[type = "checkbox"]').attr('checked','checked');
    }
    else {
        $('#' + formName + ' input[type = "checkbox"]').removeAttr('checked');
    }
}
function initTextareaAutoHeight() {
    $('textarea.regular').data('doneSetup','y');
    $('textarea').each(function(i,n) {
        setupTextareaAutoHeight(n, null);
    });
}
function setupTextareaAutoHeight(textbox, divClass) {
    var targetDiv = getTargetDivForTextbox(textbox);
    setupTextareaAutoHeight2(textbox, divClass, targetDiv);
    textbox.onpaste = function() { setTimeout(function() { sizeTextarea($(textbox), targetDiv); },500); };
}
var times = function(string, number) {
                    for (var i = 0, r = ''; i < number; i ++) r += string;
                    return r;
                };
//minimum and maximum text area size
var minTextboxHeight = 10 ;
var maxTextboxHeight = 300 ;
//increment value when resizing the text area
var growBy = 20 ;
var textStyleArray = ['padding-top', 'padding-bottom', 'padding-left', 'padding-right', 'line-height', 'font-size', 'font-family', 'font-weight', 'font-style'];
function setupTextareaAutoHeight2(textbox, divClass, targetDiv) {
    if ($(textbox).data('doneSetup') == 'y') return;

    $(textbox).css('overflow-y','hidden');
    $(textbox).height(minTextboxHeight + growBy);

    if (!targetDiv) targetDiv = getTargetDivForTextbox(textbox, divClass);

    $(textbox).keyup(function() { sizeTextarea(textbox, targetDiv); });
    //$(textbox).click(function() { sizeTextarea(textbox, targetDiv); });
    $(textbox).data('doneSetup','y');
    return targetDiv;
}
function getTargetDivForTextbox(textbox, divClass) {
    var $this       = $(textbox);
            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(textbox).innerWidth(),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);
    if (divClass) $(shadow).addClass(divClass);

    return shadow;
    /*
    var divId = (new Date()).getTime();
    if (!divClass) divClass = '';
    $('body').append('<div id="' + divId + '" style="position: absolute; top: -100000px; left: -100000px;" class="' + divClass + '"></div>');
    var targetDiv = $('#' + divId);
    for (var i = 0; i < textStyleArray.length; i++) {
        $(targetDiv).css(textStyleArray[i], $(textbox).css(textStyleArray[i]));
    }
    return targetDiv;
      */
}
function sizeTextarea(textbox, targetDiv) {
//    var text = $(textbox).val().replace(/</g, '&lt;')
//                                    .replace(/>/g, '&gt;')
//                                    .replace(/&/g, '&amp;')
//                                    .replace(/\n$/, '<br/>&nbsp;')
//                                    .replace(/\n/g, '<br/>')
//                                    .replace(/ {2,}/g, function(space) { return times('&nbsp;', space.length -1) + ' ' });

    var text = $(textbox).val().replace(/<br \/>&nbsp;/, '<br />')
                              .replace(/<|>/g, ' ')
                              .replace(/&/g,"&amp;")
                              .replace(/\n/g, '<br />&nbsp;');
    $(targetDiv).html(text);
    var textHeight = $(targetDiv).height();
    if ( textHeight > maxTextboxHeight ){
      textHeight = maxTextboxHeight ;
      $(textbox).css('overflow', 'auto');
    }
    if ( textHeight < minTextboxHeight ) {
      textHeight = minTextboxHeight ;
    }
    $(textbox).height(textHeight + growBy);
}
function resetTextareaHeight(textbox) {
    setTimeout(function() {
        $(textbox).height(minTextboxHeight + growBy).css('overflow-y','hidden');
    }, 500);
 }
function brintDPToTop(inp, dp) {
    //$('#' + dp.id).attr('readonly','true');
    $(dp.dpDiv).css("z-index", "2000");
}
function enableDateField(inp, dp) {
    //$('#' + dp.id).removeAttr('readonly');
}
function isKeyToNext(key) {
    if (key == 13 || key == 9 || key == 188 || key == 59 || key == 32) return true;
    return false;
}
function isKeyToNextAllowedSpace(key) {
    if (key == 13 || key == 9 || key == 188 || key == 59) return true;
    return false;
}
function isKeyToNextAllowedSpaceNoEnter(key) {
    if (key == 9 || key == 188 || key == 59) return true;
    return false;
}
function inEmailList(inputName, email) {
    var emails = $('#' + inputName).val();
    var tmp = emails.split(',');
    for (var i = 0; i < tmp.length; i++)
        if (tmp[i] == email) return true;
    return false;
}
function inEmailListByElem(inputElem, email) {
    var emails = $(inputElem).val();
    var tmp = emails.split(',');
    for (var i = 0; i < tmp.length; i++)
        if (tmp[i] == email) return true;
    return false;
}
function inListByElem(inputElem, email) {
    var emails = $(inputElem).val();
    var tmp = emails.split(',');
    for (var i = 0; i < tmp.length; i++)
        if (tmp[i] == email) return true;
    return false;
}
function getDateByOffset(offset) {
    // create Date object for current location
    d = new Date();

    if (offset == null || offset == '') return d;
    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));

    // return time as a string
    return nd;

}

// script by Josh Fraser (http://www.onlineaspect.com)
// return the offset in milliseconds and daylight saving. ex: -180000,1 or -180000,0 (0-no DST, 1-has DST)
function calculateZoneOffset() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2);
	var daylight_time_offset = (june1 - june2);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
//    alert(std_time_offset);
    return std_time_offset+","+dst;
}
function isValidDate(value, element) {
    var dateStr = $.trim(value);
    var targetElem = $(element).prev();
    if (dateStr == '') {
        $(targetElem).val('');
        return true;
    }
    try {
        var date = $.datepicker.parseDate( userDateFormat, dateStr );
        $(targetElem).val($.datepicker.formatDate( "mm/dd/yy", date ));
        return true;
    }
    catch (ex) {
        return false;
    }
}
function mmInsertDate(elem) {
    var dateStr = $(elem).val();
    var targetElem = $(elem).next();
    if (dateStr == '') $(targetElem).val('');
    else {
        var date = $.datepicker.parseDate( "mm/dd/yy", dateStr );
        $(targetElem).val($.datepicker.formatDate( userDateFormat, date ));
    }
}
function checkAll(cbElem, container) {
    if (cbElem.checked) {
        $(container).find('input:checkbox').attr('checked','checked');
    }
    else {
        $(container).find('input:checkbox').removeAttr('checked');
    }
}
function checkAllCb(checked, container) {
    if (checked) {
        $(container).find('input:checkbox').attr('checked','checked');
    }
    else {
        $(container).find('input:checkbox').removeAttr('checked');
    }
}
function showAddGadgetIns(type, elem) {
    var show = $(elem).html().indexOf('&gt;') > 0;
    if ($('#getGadgetDialog').hasClass('ui-dialog-content')) {
//        alert($('#getGadgetDialog .mmDialogBody').height());
        var height = show ? type == 'Apps' ? 400 : 350 : 230;
            $('#getGadgetDialog').height(height - 40);
            $('#getGadgetDialog').dialog('option','height',height);
    }
    var elemToHide;
    var altLinkElem;
    if (type == 'Apps') {
        elemToHide = $('.gSitesInsTog');
    }
    else {
        elemToHide = $('.gAppsInsTog');
    }
    altLinkElem = $(elemToHide).prev().find('span');
    $(elemToHide).hide();
    $(altLinkElem).html($(altLinkElem).html().replace('&lt;&lt;', '&gt;&gt;'));
    $(elem).html($(elem).html().replace(show ? '&gt;&gt;' : '&lt;&lt;', show ? '&lt;&lt;' : '&gt;&gt;'));
    $('.g' + type + 'InsTog').toggle();

}
function doLogo() {
    if ($('#logo').find('a').size() > 0 && !(window.location.pathname.indexOf('users/main') >= 0)) {
        $('#logo').mouseover(function() { $(this).addClass('logoHover'); }).mouseout(function() { $(this).removeClass('logoHover'); });
    }
}
function initLeftMenu(noborder) {
    $('.rightPanel').show();
    if ($('.actionMenu').size() > 0) {
        $('.actionMenu li').unbind('mouseover');
        $('.actionMenu li').unbind('mouseout');
          $('.actionMenu li[target]').mouseover(function() {
            if (!$(this).hasClass('selected') && !noborder) $(this).addClass('actionMenuHover');
          });
          $('.actionMenu li[target]').mouseout(function() {
              if (!$(this).hasClass('selected')) $(this).removeClass('actionMenuHover');
          });
//          $('.actionMenu .selected').unbind('click');
          $('.actionMenu .greyOut').unbind();
    }

    $('#leftActionMenu li[index]').click(function() {
      var index = $(this).attr('index');
      reloader.currentSection = index;
      reloader.update(index);
      var target = $(this).attr('target');
      $('.menuItem').hide();
      $('.menuItem_sub').hide();
      $('#' + target).show();
      $('#' + target + '_sub').show();
      $('#leftActionMenu li[target]').removeClass('selected').css('background-color','');
      if (!noborder) $('#leftActionMenu li[target]').css('border-bottom','1px solid #A6C9E2');
      $(this).addClass('selected').removeClass('actionMenuHover').css('border','none');
      $(this).prev().css('border-width','0px');
//            alert(pageCookie + ':' + target);
    $.cookie(pageCookie, target, { path: '/'});
//            alert($.cookie(pageCookie));
  });

  $('#leftActionMenu li[target]').each(function(i,n) {
      $('#' + $(n).attr('target')).addClass('menuItem');
      $('#' + $(n).attr('target') + '_sub').addClass('menuItem_sub');
      if ($(n).hasClass('selected')) {
          //alert($(n).attr('target'));
          currMenuIndex = $(n).attr('index');
          $(this).prev().css('border-width','0px');
      }
      else {
          $('#' + $(n).attr('target')).hide();
      }
  });

    //team switching
    $('#teamSelected').bind('change', function(){
     $('#teamSelectedForm').submit()
    });
    $('#' + $('#leftActionMenu .selected').attr('target')).show();
}
function initSuedoElem(suedoElem, targetElem, targetInput) {
    $(suedoElem).bind('click focus keydown keypress',function() {
        $(targetElem).show();
        $(this).hide();
        $(targetInput).focus();
    //            alert('test2');
    });
    $(targetInput).blur(function() {
      setTimeout(function() {
        if ($(targetInput).val() == '') {
          $(suedoElem).show();
          $(targetElem).hide();
        }
      }, 1000);
    });
}
function setUserDateFormat(locale) {
    try {
      userDateFormat = mmDateFormat[locale];
      userLanguage = locale.split('_')[0];
    }
    catch(ex) {
      userDateFormat = 'mm/dd/yy';
      userLanguage = 'en';
    }
    if (!userDateFormat) {
      userDateFormat = 'mm/dd/yy';
      userLanguage = 'en';
    }
}
