var STATUS_ERROR = 'error';
var STATUS_SUCCESS = 'success';

var yahooDialogs = new Array();


String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

function fixImgToMaxWidth(picName, maxW) {
	var pic = getElement(picName);
	w = pic.width;
	h = pic.height;
	if (w > maxW) {
		f = 1 - ((w - maxW) / w);
		pic.width=w * f;
		pic.height=h * f;
	}
}

//function trapEnter(e) {
//	var key=e.keyCode || e.which;
//	if (key==13) return false;
//}

function trapEnter(e) { return true;
    var result = true;

    if(document.all && event && ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))){
        result = false;
    }
    if(!document.all && e && ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))){
        e.cancelBubble = true;
        if(e.stopPropagation) e.stopPropagation();
        result = false;
    }
    
    return result;
}


function showLogin() {
    mX = YAHOO.util.Dom.getX('greeting');
    mY = YAHOO.util.Dom.getY('greeting');
    mX = mX - 200;

    var myLogin;
    if(yahooDialogs['pnlLogin']){
        myLogin = yahooDialogs['pnlLogin'];
        myLogin.show();
    }
    else{
        myLogin = new YAHOO.widget.Dialog("pnlLogin", { postmethod:"async", width:"250px", height:"200px", x: eval("mX") , y: eval("mY"), underlay:"none" } );
        yahooDialogs['pnlLogin'] = myLogin;
    }

    var handleSubmit = function(){
        this.submit(); 
        //this.show(); 
    };
    var b = [ { text:"Login", handler:handleSubmit, isDefault:true } ];

    var onSuccess = function(o) {
	    if ( o.responseText == "true" ) { // successful login
	        myLogin.hide();
	        window.location.href = window.location.href; // force a page reload
	    } else { // incorrect login creds
	         getElement("lblLoginStatus").innerHTML = "Login Incorrect";
	    }
    }
    var onFailure = function(o) {
	    // alert("There was an error communicating with the database. " + o.status);
    }
    myLogin.callback.success = onSuccess;
    myLogin.callback.failure = onFailure;
    myLogin.cfg.queueProperty("buttons", b);
    myLogin.submit = function() {
        if(this.validate()){
            this.beforeSubmitEvent.fire();
            this.doSubmit();
            this.submitEvent.fire();
            return true;
        }
        else{
            return false;
        }
    };
    
    myLogin.render();
    getElement("lblLoginStatus").innerHTML = "";
    getElement("txtUsername").value = "";
    getElement("txtPassword").value = "";
}

function hideLogin() {
    // clear out anything typed into the text boxes
    getElement("txtUsername").value="";
    getElement("txtPassword").value="";
    getElement("status").innerHTML="";
    getElement("login").style.visibility = "hidden";
}

function getElement(name){
	if(document.getElementById) return document.getElementById(name);
	else if(document.all) return document.all[name];
	else return null;
}

function isEmail(email)
{
    var emailPattern = /^[a-zA-Z0-9][a-zA-Z0-9\._-]*@[a-zA-Z0-9][a-zA-Z0-9\._-]*[\.][a-zA-Z0-9]{2,4}$/;
    var regex = new RegExp(emailPattern);
    return regex.test(email)
}

function isURL(u)
{
  if (u.indexOf(" ") != -1)
    return false;
  else if (u.indexOf("http://") == -1)
    return false;
  else if (u == "http://")
    return false;
  else if (u.indexOf("http://") > 0)
    return false;

  u = u.substring(7, u.length);
  if (u.indexOf(".") == -1)
    return false;
  else if (u.indexOf(".") == 0)
    return false;
  else if (u.charAt(u.length - 1) == ".")
    return false;

  if (u.indexOf("/") != -1) {
    u = u.substring(0, u.indexOf("/"));
    if (u.charAt(u.length - 1) == ".")
      return false;
  }

  if (u.indexOf(":") != -1) {
    if (u.indexOf(":") == (u.length - 1))
      return false;
    else if (u.charAt(u.indexOf(":") + 1) == ".")
      return false;
    u = u.substring(0, u.indexOf(":"));
    if (u.charAt(u.length - 1) == ".")
      return false;
  }

  return true;
}



function toTitleCase(str){
    if(str.length == 1) str = str.charAt(0).toUpperCase();
    else if(str.length > 1) str = str.charAt(0).toUpperCase() + str.substr(1).toLowerCase();

    return str;
}

function checkSubmitButton(btn, evt) {
    var result = true;
    var but = getElement(btn);

    if ((evt.which && evt.which == 13) || (evt.keyCode && evt.keyCode == 13))
    {
        result = false;
        if (but) but.click();
    }

    return result;
}

function hideSubnav() { getElement('subnav').style.visibility='hidden'; }

function doSubnavOver(section) {

    switch (section) {

        case '2': // My artCloud
            d = getElement('subnav');
            d.innerHTML = '<a href="../myartcloud/profile.php" class="sub">My profile</a> | <a href="../portfolio/portfolio_home.php" class="sub">My portfolios</a> | <a href="../myartcloud/myGroups.php" class="sub">My groups</a> | <a href="../myartcloud/messages.php" class="sub">My messages</a> | <a href="../myartcloud/account.php" class="sub">My account</a>';
            d.style.paddingLeft = "76px";
			d.style.visibility='visible';
            break;
        case '3': // Friends
            d = getElement('subnav');
			d.innerHTML = '<a href="../friends/myfriends.php" class="sub">My friends</a> | <a href="../friends/findfriends.php" class="sub">Find a friend</a>';
			d.style.paddingLeft = "190px";
            d.style.visibility='visible';
            break;
        case '4': // Groups
            d = getElement('subnav');
            d.innerHTML = '<a href="../groups/groups_home.php" class="sub">Most popular groups</a> | <a href="../groups/groups_home.php?s=r" class="sub">Newest</a> | <a href="../groups/groups_home.php?s=a" class="sub">View all (A-Z)</a> | <a href="../groups/search_groups.php" class="sub">Search/Browse</a> | <a href="../groups/create_group.php" class="sub">Create a group</a>';
            d.style.paddingLeft = "20px";
            d.style.visibility='visible';
            break;
        default:
            hideSubnav();
            break;
    }
}

function isDate(dtStr)
{
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date");
		return false;
	}
    return true;
}

function addLoadEvent(f) {
  var args = addLoadEvent.arguments;
  var orig = window.onload;

  if (typeof window.onload != 'function') {
    if(args.length > 1){
        window.onload = function(){
            f(args[1]);
        };
    }
    else window.onload = f;
  } else {
    window.onload = function() {
      if (orig) {
        orig();
      }
      if(args.length > 1) f(args[1]);
      else f();
    }
  }
}

function displayStatusMessage(elID, state, msg){
    var span = getElement(elID);

    if(span){
        var html = '';
        if(msg.length > 0){
	        html = '<table cellspacing="0" class="status_'+ state + '"><tr>';
	        html += '<td>' + msg +'</td>';
	        html += '</tr></table><br />';
	    }
	    span.innerHTML = html;
	}
	return html;
}

function displayDialogStatusMessage(elID, state, msg){
    var span = getElement(elID);

    if(span){
        var html = '';
        if(msg.length > 0){
	        html = '<table cellspacing="0" class="status_dialog_'+ state + '"><tr>';
	        html += '<td>' + msg +'</td>';
	        html += '</tr></table><br />';
	    }
	    span.innerHTML = html;
	}
	return html;
}

// star rating fcns
function rOver(el, r) {
	x = 1;
	while (x <= r) {
		elName = el + "_" + x;
		img = getElement(elName);
		img.src= '../images/star_on.gif';
		x++;
	}
}

function rOut(el, r) {
	x = 1;
	while (x <= r) {
		elName = el + "_" + x;
		img = getElement(elName);
		img.src= '../images/star_off.gif';
		x++;
	}
}

/*
    Tooltip for header sections.
*/
var sectionTooltips = new Array();
sectionTooltips['ttProfile'] = "In My profile, fill out all the sections you'd like. You can edit any entries you make by clicking on " + '"Edit."' + 'Only the sections you fill in will be visible to others.';
sectionTooltips['ttMyPortfolio'] = 'In My portfolios, you can create as many groups of images, videos, sounds and PDF files as you like. You could do one for a specific series of works, or all the images in a show, or by type (such as drawings or videos). We recommend that you keep the file sizes as small as possible so that uploading the files will be faster. We are limiting the file size for the moment to 5 megabytes for each picture, sound and PDF file, and 20 megabytes for each video file. Click on "View all" to see all the images in your portfolios together.';
sectionTooltips['ttPortfolioLarge'] = sectionTooltips['ttMyPortfolio'];
sectionTooltips['ttPortfolioAll'] = sectionTooltips['ttMyPortfolio'];
sectionTooltips['ttMyGroups'] = 'In My groups, see the groups you have been invited to join and that you\'re a member of now. You can also search groups by typing in a subject that interests you. If you don\'t find that subject and would like to form a new group related to your interest, you can do it in the "Create a group" area.';
sectionTooltips['ttMessages'] = 'In My messages, you can write and send messages inside artCloud to other artCloud members. You can see messages in your Inbox and Sent box. You can delete messages and mark them as read or unread. You can\'t send messages to people\'s email accounts (for example, you can\'t mail to someone\'s gmail or AOL accounts). Note: You can see if you have messages on the home page where you see this icon: <img src="../images/new_message.gif" alt="" />.';
sectionTooltips['ttAccount'] = 'In My account, you can choose who can see your profile, your list of friends, and who you will accept artCloud messages from. You can keep your account as private as you like, sharing with no one, with select friends or with everyone. You can also go to your settings for your profile from this page.';
sectionTooltips['ttMyFriends'] = 'In My friends, you can see a list of all of your friends or see specific categories of friends, based on artCloud\'s different categories of art professionals and organizations. You can also invite an artCloud friend to an event by sending them a quick message-just click on the "Invite a member" link in the My Friends bar. Note: You\'ll need to know the member\'s username to send them your quick message. You can find artCloud friends by clicking on Find a friend in the My Friends bar.';
sectionTooltips['ttFindFriends'] = 'In Find a friend, you can quickly find other artCloud members you\'d like to invite to be friends by typing in their artCloud username or their email address or by looking for artCloud members by where they live. Once you\'ve found members, you can invite them to be friends, send them messages, and view their portfolios.';
sectionTooltips['ttGroupsBelong'] = 'In My groups, see the groups you currently belong to. You can also click on the "Create a group" link in the My groups bar to start a new group.';
sectionTooltips['ttPopularGroups'] = 'In both the Most popular and Newest groups areas, you can view the groups that the most people have joined or view the most recently created groups. You can view each group or join it. You\'ll also see the groups you currently belong to.';
sectionTooltips['ttAllGroups'] = 'In View all groups (A-Z), you can see all of artCloud\'s groups in alphabetical order. You can view each group and join it.';
sectionTooltips['ttSearchGroups'] = 'In Search/Browse groups, type in keywords that are relevant to the group that you\'re looking for. You can use more than one keyword by typing AND between the words (for example, Berlin AND galleries). On the upper right of the Search/Browse screen, you can choose to sort the results of your search by how close they are to the keywords you typed in or by the date that the group was started.';
sectionTooltips['ttCreateGroup'] = 'In Create a group, you can name the group you\'d like to start, insert a picture that represents the group, describe what the group is about, make the group public or private, open to all or by invitation only to other artCloud members. You can also link to the Search/Browse groups area from the Create a group bar.';
sectionTooltips['ttInvite'] = 'You can easily invite other people to join artCloud-and we hope you will! Just send them an email and they\'ll get an invitation with links back to artCloud. The message will say that you\'ve invited them to join and briefly describes artCloud\'s features. You can invite up to five people at a time by entering five email addresses with a comma between each one.';
sectionTooltips['ttWorldCal'] = 'World calendar brings you hundreds of exhibition announcements each month taking place all over the world. During any given week, you\'ll find new listings. Be sure to add them to your own calendar on artCloud-My calendar-before they are replaced with new listings every Sunday night. You can click on a calendar date and go to that day\'s listings or click on an event in the World Art Events listings on the main screen. Either way, you can add the events that interest you to your own calendar. You can click on the event\'s title and get a new window popup of the event sponsor\'s website or you can click to get a Google map of the event\'s location. You can email the event to anyone you\'d like (up to five email addresses at a time with commas between each one). You can also "tag" an event, which means that you can type in a word that describes the event (for example: photography, color, fish, afternoon, river, France), which will be added to artCloud\'s list of tags that makes searching artCloud for what interests you really easy. Type in as many relevant tags as you want (with a comma between each one). You can also sort events on each day\'s listings page by title or by city.';
sectionTooltips['ttMyCal'] = 'You can add events from the World calendar to your own calendar (My calendar). You can click on a highlighted date to see what you\'ve added to your calendar for that date. You can create a new event by clicking on the "Create event" link at the bottom of the calendar. Your event will be added to your calendar and you can make it private (only you will see it) or you can email the event to up to five friends at a time (be sure to put a comma between each email address). You can click on the event\'s title and get a new window popup of the event sponsor\'s website or you can click to get a Google map of the event\'s location. You can also “tag” an event, which means that you can type in a word that describes the event (for example: photography, color, fish, afternoon, river, France), which will be added to artCloud\'s list of tags that makes searching artCloud for what interests you really easy. Type in as many relevant tags as you want (with a comma between each one). You can also sort events on each day\'s listings page by title or by city.';


/**
    ctx - the context
    body - the tooltip body
    [width] - the width of the tooltip (pls include units, or auto). Default = 300px
    [autodismissdelay] - the dismiss delay in milliseconds. Default = 15000 ms
*/
function yahooTooltip(ctx, body){
    var args = yahooTooltip.arguments;
    var w = (args.length > 2 ? args[2] : "300px");
    var dismisdelay = (args.length > 3 ? args[3] : 15000);
    var tipID = 'stt' + ctx;
    var obj = new YAHOO.widget.Tooltip(tipID, { effect: { effect:YAHOO.widget.ContainerEffect.FADE, duration:0.25 }, width:w, preventoverlap:true, autodismissdelay:dismisdelay, context:ctx, text:body } );
    
    return obj;
}

function initSectionHeaderTooltip(id){
    yahooTooltip(id, sectionTooltips[id]);
}
