/**
 * Help on javascript cookie manipulation can be found at http://www.quirksmode.org/js/cookies.html
 **/

/** can also be used to update a value of a cookie **/
function createCookie(name,value,days) {
  if( days ){
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }else{ 
    expires = "";
  }
  document.cookie = name+"="+value+expires+"; path=/";
}

function getCookieValue(cookieName){
    var cookieValue = document.cookie;
    var cookieStartsAt = cookieValue.indexOf(cookieName+"=");
    if( cookieStartsAt == -1 ){
        cookieValue = null;
    }else{
        cookieStartsAt = cookieValue.indexOf("=",cookieStartsAt)+1;
        var cookieEndsAt = cookieValue.indexOf(";",cookieStartsAt);
        if( cookieEndsAt == -1 ){
            cookieEndsAt = cookieValue.length;
        }
        cookieValue = unescape(cookieValue.substring(cookieStartsAt,cookieEndsAt));
    }
    return cookieValue;
}

function getKundeEpostCookieValue(){
    var cookieValue = getCookieValue("klientEpost");
    if( cookieValue != null ){
        cookieValue = replaceAll(cookieValue, " AT ","@");
        cookieValue = replaceAll(cookieValue, '"' ,'');
    }else{
        cookieValue = "";
    }
    return cookieValue;
}


function replaceAll(oldStr,findStr,repStr) {
    // Code from Philip Tan Boon Yew.
    // See http://home1.pacific.net.sg/~firehzrd/jsarc/unWebify.html
  var srchNdx = 0;  
  var newStr = "";  
  while( oldStr.indexOf(findStr,srchNdx) != -1 ){
    newStr += oldStr.substring( srchNdx,oldStr.indexOf(findStr,srchNdx) );
    newStr += repStr;
    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
  }
  newStr += oldStr.substring(srchNdx,oldStr.length);
  return newStr;
}

function insertKundeEpost(field) {
    return updateField(field, 'Din e-post', getKundeEpostCookieValue());
}   

function updateField(field, oldText, newText){
    if (field != null && field.value == oldText) {
        field.value = newText;
        field.focus()
        return true;
    }
}