var USER_COOKIE = "glinkme.user";
var HISTORY_COOKIE="history";
var NEXT_PAGE_COOKIE="next.page";
var LOGIN_MESSAGE="login.message";
var REMEMBER_USER="remember.me";
var COOKIE_TIMEOUT=15;

  function body_onload()
  {
    //overwrite by the page loading!
  }

  function toLowerCase( obj )
  {
    obj.value=obj.value.toLowerCase();
  }
  
  function hideSignup_message()
  {
    getHtmlElement('result').style.display="none";
  }

  function signup_message( sMessage )
  {
    getHtmlElement('result').style.display="block";
    getHtmlElement('result').innerHTML="<center>"+sMessage+"</center>";
    round("result");
  }
  
  function isValidEmail( sEmail )
  {
      var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return emailRegEx.test( sEmail );
  }
  
  /* signup.php */
  function saveFormProfile()
  {
    hideSignup_message();
    if( getHtmlElement('Email').value == "" )
    {
      signup_message("Please fill out the email field!");
      getHtmlElement('Email').focus();
      return false;
    }
    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if( !isValidEmail( getHtmlElement('Email').value ) )
    {
      signup_message("Please specify a valid email address!");
      getHtmlElement('Email').select();
      return false;
    }
    if( getHtmlElement('Password').value.length < 6 )
    {
      signup_message("Passwords must be minimum 6 characters.");
      getHtmlElement('Password').select();
      return false;
    }
    if( getHtmlElement('Password').value != getHtmlElement('Password2').value )
    {
      signup_message("The two passwords are not equal! Try again please.");
      getHtmlElement('Password').select();
      return false;
    }
 
    var oProfile = getFormProfile();   
    var url = "php/php_save_profile.php?Save=Profile"+oProfile.toUrlString();
    ajaxCall( url, _saveResult );
  }
  
  function _saveResult( request )
  {
    var xml = request.responseXML;
    if( getNodeValue( xml, "error") != null )
    {
      signup_message( getNodeValue( xml, "error" ) );
    }
    if( getNodeValue( xml, "success") != null )
    {
      var sId = getNodeValue( xml, "success");
      signup_message("Profile saved! You will receive a confirmation email on the given address. The email will contain a link to use for your profile to be activated.<br><div id='resultSent'/>");
      var url="php/php_activate_profile.php?SendActivation="+sId;
      ajaxCall( url, _mailSendResult );
    }
   }
  
  function _mailSendResult( request )
  {
      getHtmlElement('resultSent').innerHTML = "<center><br>"+request.responseText+"</br></center>";
  }
  
  function getFormProfile()
  {
    var oProfile = new Profile();
    oProfile.Email = getHtmlElement('Email').value;
    oProfile.Password=hex_md5(getHtmlElement('Password').value);
    oProfile.ActivationCode="";
    return oProfile;
  }
  

  //Will insert the profiles tags into tagLinks
  function getProfileTags()
  {
      var url="php/php_tags.php?email="+readCookie( USER_COOKIE );
      ajaxCall( url, getTagsResult );
  }
  
  function getTagsResult( request )
  {
    if( request.responseText != "")
    {
      loadTagCollectionResult( request, setUserTagLinks )    
    }
  }
  
  function getPopularTags()
  {
    loadTagCollection( "where Count>5 order by TagName", getPopularTagsResult );
  }
   function getWeightArray( tagArray )
  {
    var max=0;min=1;
    for( var i =0 ;i<tagArray.length ; i++ )
    {
      t=tagArray[i].Count;
      if( max < t )
        max = t;
      if( min > t )
        min = t;
    }
    var weightArray = new Array();
    var middle=mid( min,max );
    weightArray[0]=min;
    weightArray[1]=mid(min,middle);
    weightArray[2]=middle;
    weightArray[3]=mid(middle,max);
    weightArray[4]=max;
    //document.write( weightArray );
    return weightArray;
  }

  function mid( min, max )
  {
    return Math.round(min+((max-min)/2));  
  } 

  function getPopularTagsResult( tagArray )
  {
    var links = getTagLinks( tagArray, getWeightArray(tagArray) );
    getHtmlElement("popularTags").appendChild( links );
  }

  function setUserTagLinks( tagArray )
  {
    var links = getTagLinks( tagArray, getWeightArray(tagArray) );
    getHtmlElement("tagLinks").appendChild( links );
    round("tagLinks");   
  }
  
  function getTagLinks( tagArray, tagBounds )
  {
      var fragment = document.createDocumentFragment();
      for(var i=0; i< tagArray.length; i++ )
      {
        fragment.appendChild( createTagLink(tagArray[i], tagBounds ) );
      }
      return fragment;
  }
  
  var tagSizes = new Array( "x-small" ,"small", "medium",  "large",  "x-large" );
  var tagColor= new Array( "gray",  "navy",  "Brown",  "teal",  "maroon" );
  function createTagLink( oTag, tagBounds )
  {
    var size=null;
    var color=null;
    for(var i=0; (i < tagBounds.length && !size); i++ )
    {
      if( oTag.Count <= tagBounds[i] ){
        size=tagSizes[i];
        color=tagColor[i];
      }
    }
    var a = document.createElement("a");
    a.className="tag";
    a.style.fontSize=size;
    a.style['color']=color;
    var hrf = "javascript:addTag('"+oTag.TagName+"')";
    a.href=hrf;
    //a.setAttribute("href", hrf );
    a.appendChild( document.createTextNode( oTag.TagName + " " ) );
    return a;
  }
  
  function addTag( sTag )
  {
    if( document.getElementById('tags').value.toLowerCase().indexOf(sTag) == -1 )
      document.getElementById('tags').value += " " + sTag;
  }

  function post_init()
  {
    var urlTarget = document.getElementById('url');
    var index=window.location.href.indexOf('?');
    if( index != -1 )
    {
      urlTarget.value = window.location.href.substr( index +1 );
      document.getElementById('tags').focus()
    }
    else
      urlTarget.focus();
    //create tag links  
    var tagDiv = document.getElementById('tagLinks');
    var sTagHtml ="";
    for( var i=0; i < mTags.length; i++ )
    {
        sTagHtml += createTagLink( mTags[i], userTagTable ) + " ";
    }
    tagDiv.innerHTML = sTagHtml;
  }
  
  function setSubmit()
  {
    getHtmlElement('tags').value=getHtmlElement('tags').value.toLowerCase();
    return true;
  } 

  function loginProfile()
  {
    hideLoginMessage();

    var email = getHtmlElement('Login_Email').value;
    if( email=="" )
    {
      setLoginMessage("Please specify email", "warning");
      return;
    }
    var password = getHtmlElement('Login_Password').value;
    if( password=="" )
    {
      setLoginMessage("Please specify password", "warning");
      return;
    }

    var url="php/php_login.php?login="+escape(email)+"&password="+hex_md5(password);
    ajaxCall( url, loginProfileResult );
  }
  
  function setLoginMessage( sMessage, sClassName )
  {
    getHtmlElement("userMessage").style.display="block";
    getHtmlElement("userMessage").innerHTML="<center><b>"+sMessage+"</b></center>";
    round("userMessage");
  }

  function hideLoginMessage()
  {
    getHtmlElement("userMessage").style.display="none";
  }
  
  function loginProfileResult( request )
  {
    var xml = request.responseXML;
    if( getNodeValue( xml, 'success' ) != null )
    {
      var expire = getHtmlElement("rememberMe").checked ? COOKIE_TIMEOUT : null;
      createCookie( USER_COOKIE, getNodeValue( xml, "success"), expire );

      if( getHtmlElement('rememberMe').checked )
        createCookie( REMEMBER_USER, "true", COOKIE_TIMEOUT ); 
      else
        deleteCookie( REMEMBER_USER );
      
      if( readCookie( NEXT_PAGE_COOKIE ) != null )
      {
        var nextPage = readCookie( NEXT_PAGE_COOKIE );
        deleteCookie( NEXT_PAGE_COOKIE );
        window.location.href=nextPage;        
      }
      else
        window.location.href=window.location.href;
    }
    else if ( getNodeValue(xml, "error" ) ) 
      setLoginMessage( getNodeValue( xml, 'error' ), "warning" );
  }
  
  function logoutProfile()
  {
    deleteCookie( USER_COOKIE );
    window.location.href=window.location.href;
  }

  function deleteProfile( sId, callBack )
  {
    var url="php/php_delete_profile.php?user="+sId;
    ajaxCall( url, callBack );              
  }  

  function submitPost()
  {
    if( getHtmlElement("tags").value == "" )
    {
      alert("You must specify at least one tag.");
      getHtmlElement("tags").focus();
      return false;
    }
    getHtmlElement("postbutton").innerHTML="<b>posting<blink>...</blink></b>";
    var title=getHtmlElement("title").value;
    var url=getHtmlElement("url").value;
    var tags=getHtmlElement("tags").value;
    var description=getHtmlElement("description").value;
    var url="/php/php_post.php?user=" + readCookie( USER_COOKIE ) +"&title="+escape(title)+"&url="+url+"&description="+escape(description)+"&tags="+escape(tags);
    ajaxCall( url, submitPostResult );
    window.status="Posting...";
  }
  
  function submitPostResult( request )
  {
   getHtmlElement("postbutton").innerHTML="<b>Done!</b>";
   if( readCookie( HISTORY_COOKIE ) != null )
    {
      var sUrl = readCookie( HISTORY_COOKIE );
      deleteCookie( HISTORY_COOKIE );
      window.location.href = unescape(sUrl); 
    }
    else
    {
      window.close();
    }    
  }
  
  function updatePostLink()
  {
    var url="/php/php_postlink.php?user=" + readCookie( USER_COOKIE );
    ajaxCall( url, updatePostLinkResult );
  }
  
  function updatePostLinkResult( request )
  {
    var xml = request.responseXML;
    getHtmlElement("postLink").innerHTML = getNodeValue(xml, "link" );
  }

  function displayPostLink( bShowIt )
  {
     getHtmlElement("postLink").style.display = (bShowIt ? "block" : "none");
     round("postLink");
  }
  
  function round( elementId, sBackground, sForground )
  {
    var elem = document.getElementById( elementId );
    if( sBackground == null )
    {
      sBackground = elem.parentNode.style.backgroundColor;
      sForground = elem.style.backgroundColor; 
      //alert(elem.parentNode + " " + sBackground );
      //alert(elem + " " + sForground );
    } 
    var bRTop=getRTop( sBackground, sForground );
    elem.insertBefore( bRTop, elem.firstChild );
    var bRBottom = getRBottom( sBackground, sForground );
    elem.appendChild( bRBottom );
  }
  function getB( sClassName, sColor )
  {
    var b= document.createElement("b");
    b.style.backgroundColor=sColor;
    b.className = sClassName;
    return b;
  }
  function getRTop( sBackground, sForground )
  {
    var b=getB( "rtop", sForground );
    b.style.backgroundColor=sBackground;
    b.appendChild( getB("r1", sForground ) );
    b.appendChild( getB("r2", sForground ) );
    b.appendChild( getB("r3", sForground ) );
    b.appendChild( getB("r4", sForground ) );
    return b;
  }
   function getRBottom( sBackground, sForground )
  {
    var b=getB( "rbottom", sForground );
    b.style.backgroundColor=sBackground;
    b.appendChild( getB("r4", sForground ) );
    b.appendChild( getB("r3", sForground ) );
    b.appendChild( getB("r2", sForground ) );
    b.appendChild( getB("r1", sForground ) );
    return b;
  } 
  
  function setEmailResponse( sMessage )
  {
    var resultDiv = getHtmlElement("postEmailResult");
    resultDiv.innerHTML="<center>"+sMessage+"</center>";
    resultDiv.style.display="block";
    round( "postEmailResult" );
  }
  
  function postEmail()
  {
    var subject=getHtmlElement("subject").value;
    var from=getHtmlElement("from").value;
    var message=getHtmlElement("message").value;
    if( !isValidEmail( from ) )
    {
      setEmailResponse("Specify a valid email please");
      getHtmlElement("from").focus();
      return false;
    }
    if( subject == "" )
    {
      setEmailResponse("Specify a subject");
      getHtmlElement("subject").focus();
      return false;
    }
    if( message == "" )
    {
      setEmailResponse("Specify the message...");
      getHtmlElement("message").focus();
      return false;    
    }
    getHtmlElement("postEmailResult").style.display="none";
    var url="php/php_post_email.php?subject="+escape(subject)+"&from="+escape(from)+"&message=" +escape(message);
    ajaxCall( url, postEmailResult );
  }
  
  function postEmailResult( request )
  {
    setEmailResponse( request.responseText );
  }

  function deleteAccount()
  {
    if( !confirm("You are about to delete your account, and all your tag information. Are you sure?!") )
      return false;
    deleteProfile( readCookie( USER_COOKIE ), deleteAccount_result )
  }
  function deleteAccount_result( request )
  {
    alert( request.responseText );
    logoutProfile();
  }
