function search(fieldid)
{
    var kwd = document.getElementById(fieldid).value;;
    window.location="search.aspx?kwd="+kwd;
}

function getPopupEnv()
{
    var popup = document.getElementById('envelope');
    if(popup==null)
    {
        popup = document.body.insertBefore(document.createElement("div"), document.body.firstChild);
        popup.id = 'envelope'; 
    }   
    popup.style.position = 'absolute';
    popup.style.display = 'block';
    popup.style.zIndex = 9999;
    return popup;
}

function hideLoading()
{
    var loading = document.getElementById('loading');
    if(loading)
    {
        loading.style.display="none";
    }
}

var xoff, yoff;
function popupWin(event, xo, yo, name, val, source)
{
    xoff = xo;
    yoff = yo;
    var aid = getAccountId();
    findMousePos(event);
    Story.WebService.GetPopup(aid, name, val, source, onGetPopupComplete);
}

function onGetPopupComplete(result)
{
    var popup = getPopupEnv();
    popup.style.top = (y+yoff) + 'px';
    popup.style.left = (x+xoff) + 'px';
    popup.innerHTML = result;

    setFocus("emailaddress");
    setFocus("fgemailaddress");
}

function setFocus(id)
{
    var inputobj = document.getElementById(id);
    if(inputobj)
    {
        inputobj.focus();
    }
}

function getAccountId()
{
    var aid = document.getElementById("AID");
    if(aid && aid.value.length>10)
    {
        return aid.value;
    }
    
    return "2E6BD115-68A7-4925-92E0-165CE81F41C6";
}

function closePopup()
{
    var envelope = document.getElementById("envelope");
    if(envelope)
    {
        envelope.style.display="none";
    }
    var titleSpan = document.getElementById("titleSpan");
    if(titleSpan)
    {
        titleSpan.style.display="none";
    }
    
}

function isValidEmail(email)
{
    return email.indexOf("@")>0 && email.indexOf(".")>0;    
}

function showError(message)
{
    var error = document.getElementById('error');
    if(error)
    {
        error.innerHTML = message;
    }
    else
    {
        alert(message);
    }
}

var source;
function createArtist(source)
{
    this.source = source;
    var emailaddress = document.getElementById('emailaddress').value;
    var artistname = document.getElementById('artistname').value;
    var password = document.getElementById('password').value;
    var terms = document.getElementById('terms');
    if(emailaddress.trim().length==0)
    {
        showError("Email address is required");
        return;
    }
    else if(!isValidEmail(emailaddress))
    {
        showError("Email address is invalid");
        return;
    }
    else if(artistname.trim().length==0)
    {
        showError("Artist name is required");
        return;
    }
    else if(password.trim().length==0)
    {
        showError("Password is required");
        return;
    }
    else if(!terms.checked)
    {
        showError("Please check the terms of use");
        return;
    }
    
    Story.WebService.CreateArtist(artistname, emailaddress, password, source, onLoginArtistComplete);
}

function loginArtist(source)
{
    this.source = source;
    var emailaddress = document.getElementById('emailaddress').value;
    var password = document.getElementById('password').value;
    if(emailaddress.trim().length==0)
    {
        showError("Email address is required");
        return;
    }
    else if(!isValidEmail(emailaddress))
    {
        showError("Email address is invalid");
        return;
    }
    else if(password.trim().length==0)
    {
        showError("Password is required");
        return;
    }
    
    Story.WebService.LoginArtist(emailaddress, password, onLoginArtistComplete);
}

function onLoginArtistComplete(result)
{

    if(result=="ok")
    {
        if(source!="")
        {
            window.location = "/" + source + "/myaccount.aspx";
        }
        else
        {
            window.location = "myaccount.aspx";
        }
    }
    else
    {
        if(result.indexOf("duplicate key")>-1)
        {
            showError("This email address has already been registered with Comicater, please use another email address.");
        }
        else
        {
            showError(result);
        }
    }
}

function sendShareEmail(bid)
{
    var emailaddress = document.getElementById("emailaddress").value;
    var message = document.getElementById("message").value;
    Story.WebService.SendShareEmail(emailaddress, message, bid, onSendEmailComplete);
}

function onSendEmailComplete(result)
{
    if(result=="ok")
    {
        closePopup();
    }
}

// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

// Global object to hold drag information.

var browser = new Browser();
var dragObj = new Object();
dragObj.zIndex = 0;
var x, y;

function dragStart(event, id) {

  var el;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  findMousePos(event);

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  findMousePos(event);

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Clear the drag element global.

  dragObj.elNode = null;

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

function findMousePos(event)
{
    if (browser.isIE) {
        x = window.event.clientX + document.documentElement.scrollLeft
          + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop
          + document.body.scrollTop;
    }
    if (browser.isNS) {
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
    }
}


function hideHint()
{
    var PopupTitle = document.getElementById("titleSpan");
    if(PopupTitle)
    {
        PopupTitle.innerHTML = '';
        PopupTitle.style.display = 'none';
    }
    else
    {
        alert("no popup element - titleSpan");
    }
}

function showHint(img, showhint)
{
    var ttitle = getTitle(img.src.substring(img.src.indexOf("/clipart/")+9));
    if(showhint==0)
    {   
        showMessage(img, ttitle, "drag this image to the comic", 0, 0);
    }
    else if(showhint==1)
    {   
        showMessage(img, ttitle, "double click on image to get related clipart", 0, 0);
    }
    else if(showhint==2)
    {
        showMessage(img, "uploaded image", "double click on image to get related images", 0, 0);
    }
    else if(showhint==3)
    {
        showMessage(img, "uploaded image", "drag this image to the comic", 0, 0);
    }
    else if(showhint==4)
    {
        showMessage(img, "basic image", "drag this image to the comic", 0, 0);
    }
}

function showMessage(obj, message, hint, xoff, yoff)
{
    if(message==""&&hint=="") return;
	var targPos    = getPosition(obj);
    var PopupTitle = document.getElementById("titleSpan");
    if(PopupTitle)
    {
        PopupTitle.innerHTML = "<b>" + message + "</b>";
        if(hint) PopupTitle.innerHTML += "<br /><span style=\"color:#333;\">" + hint + "</span>";
        PopupTitle.style.left = (targPos.x+50+xoff) + "px";
        PopupTitle.style.top = (targPos.y-50+yoff) + "px";
        PopupTitle.style.display = 'block';
    }
    else
    {
        alert("no popup element - titleSpan");
    }
}

function getTitle(ttitle)
{
	ttitle = ttitle.substring(ttitle.indexOf("/")+1);
	ttitle = ttitle.replace(/mc_dd.gif/g, "");
	ttitle = ttitle.replace(/mc.gif/g, "");
	ttitle = ttitle.replace(/_lc.gif/g, "");
	ttitle = ttitle.replace(/_dd.gif/g, "");
	ttitle = ttitle.replace(/_/g, " ");
	ttitle = ttitle.replace(/\//g, " ");
	ttitle = ttitle.replace(/.gif/g, "");
	ttitle = ttitle.trim();
	var len = ttitle.length;
    var index = ttitle.lastIndexOf(" ");
	if(index==len-2&&index>0&&len>15)
	{
	    ttitle = ttitle.substring(0, len-2);
	}
	len = ttitle.indexOf(" ");
	ttitle = "<span style=\"color:#000;\">" + ttitle.substring(0, len) + " : </span>" + ttitle.substring(len);
	return ttitle;
}

String.prototype.startsWith = function(str)
{return (this.match("^"+str)==str)}

String.prototype.endsWith = function(str)
{return (this.match(str+"^")==str)}

function getCookie(c_name)
{
    if (document.cookie.length>0)
    {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1)
        { 
            c_start=c_start + c_name.length+1; 
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        } 
    }
    return "";
}

function setCookie(c_name,value,expiredays)
{
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function backtogallery(isfb) {
    var fbdir = "";
    if (isfb) fbdir = "fb/";
    var galleryurl = getCookie("galleryurl");
    if (galleryurl) {
        window.location = fbdir + galleryurl;
    }
    else {
        window.location = fbdir + "default.aspx";
    }
}

function showdiv(id, show)
{
    var div = document.getElementById(id);
    if(div)
    {
        div.style.display = show;
    }
}

function refreshpage() {
    var url = window.location.href.toString();
    if (url.endsWith("#")) {
        url = url.substring(0, url.length - 1);
    }
    window.location = url;
}
