﻿// JScript File

function goToPage(pId, e)
{    
    showLoading();
    var _id = GetCPageControlId();
    var curPage = $get(_id);
    var btnUpdate = getUpdateButton();
    curPage.value = pId;
    btnUpdate.click();    
}

function showLoading()
{
    var loadPanel = $get("loadingMsg");
    var loadImage = $get("loadImage");
    var viewPanel = $get("PageViewer");
    
    var _w = viewPanel.offsetWidth;
    var _h = viewPanel.offsetHeight;
    
    if(getBrowserType() == 0)
    {
        var _x = recurseOffset(viewPanel, 0, true) + 14;
        var _y = recurseOffset(viewPanel, 0, false) + 14;
    }
    else
    {
        var _x = viewPanel.offsetLeft;
        var _y = viewPanel.offsetTop;
    }
    loadPanel.style.width = _w + "px";
    loadPanel.style.height = _h + "px";
    loadPanel.style.left = _x + "px";
    loadPanel.style.top = _y + "px";
    loadPanel.style.display = "block";
    loadImage.style.left = _x + 260 + "px";
    loadImage.style.top = _y + 200 + "px";
    loadImage.style.display = "block";
}

function clearLoading()
{
    var loadPanel = $get("loadingMsg");
    var loadImage = $get("loadImage");
    loadPanel.style.display = "none";
    loadImage.style.display = "none";
}

function recurseOffset(oObj, iCount, bLeft) {
    // recursively bubble down the document and add up the offset left/top for div's table's and td's
    if (oObj.nodeName == "DIV" || oObj.nodeName == "TABLE" || oObj.nodeName == "TD") {
        bLeft ? iCount += (oObj.offsetLeft ) : iCount += (oObj.offsetTop );
    }
    if (oObj.parentNode && ((bLeft && oObj.parentNode.offsetLeft != null) || (!bLeft && oObj.parentNode.offsetTop != null))) { 
        iCount = recurseOffset(oObj.parentNode, iCount, bLeft);
    }
    return iCount;
}

//--------------------------------------
//Adding new album event
//--------------------------------------
function showAddPanel()
{  
    var _panel = $get("newAlbumPanel");
    var btnAddAlbum = $get("btnNewAlbum");
    var vMsg = $get("validMsg");
    if(vMsg) vMsg.style.display = "none";
    
    if(_panel.style.display!="block")
    {
        var panelBounds = Sys.UI.DomElement.getBounds(btnAddAlbum);
        _panel.style.display = "block";
        _panel.style.top = (panelBounds.y + panelBounds.height) + "px";
        _panel.style.left = (panelBounds.x + panelBounds.width - _panel.offsetWidth) + "px";         
    }   
}

/*---------------------------------------
-----------------------------------------
 Album Cover Event Handlers
-----------------------------------------
----------------------------------------*/
var notePanels = new Array();
function addAlbumObjects()
{
    showUpdateMessage("off");
    if(notePanels.length == 0)
    { 
        var iAlbums = document.getElementsByName("iPAlbum");
        var nAlbums = document.getElementsByName("nPAlbum");

        for(i=0;i<iAlbums.length;i++)
        {
            if(iAlbums[i].tagName == "INPUT")
                addGBAlbumObject(iAlbums[i].parentNode.id, nAlbums[i].parentNode.id);
        }
     }
}

//Add event handler to GB Feature Album
function addGBAlbumObject(coverId, noteId)
{    
    var coverObj = $get(coverId);
        
    var notePanel = $get(noteId);
    var i = notePanels.length;
    notePanels[i] = notePanel;
}

function isMouseLeaveOrEnter(e, handler)
{		
	var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (reltg && reltg != handler) reltg = reltg.parentNode;
	return (reltg != handler);
}

function showNoteOn(e, handler)
{
    e = e || window.event;
    
    if(isMouseLeaveOrEnter(e, handler))
    {
        showNoteMessage("on", handler);
    }
}

function showNoteOff(e, handler)
{
    e = e || window.event;
    
    if(isMouseLeaveOrEnter(e, handler))
    {
        showNoteMessage("off", handler);
    }    
}

function showNoteMessage(action, target)
{    
    if(target.id.indexOf("iGBAlbum") != -1 || target.id.indexOf("iPAlbum") != -1 )
    {
        var id = "n" + target.id.substr(1);
        notePanel = $get(id);
    }   
    
    if(action == "on" && notePanel)
    {
        notePanel.style.display = "block";
        notePanel.style.left = "0px";
        notePanel.style.top = "0px";
    }
    if(action == "off" && notePanels)
    {
        var i;
        for(i=0;i<notePanels.length;i++)
        {
            var _ID = notePanels[i].id;
            //var temp = $get(_ID);
            //temp.style.display = "none";
            notePanels[i].style.display = "none";
        }
    }  
}

function setEditable(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    
    if(target)
    {
        target.style.background = "yellow";    
    }
}

function resetTitle(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    
    if(target)
    {
        target.style.background = "lightgrey";    
    }
}

function closePanel(id)
{
    if(id=="newAlbumPanel")
    {
        var target = $get(id);
        var tbxTitle = $get("tbxAlbumTitle");
        var selVisibleTo = $get("selVisibleTo");
        var vMsg = $get("validMsg");
        
        if(vMsg) vMsg.style.display = "none";
        target.style.display = "none";
        tbxTitle.value = "";
        selVisibleTo.value = "-1";        
    }
}

/*----------------------------*/
//  Create New Album
/*----------------------------*/
function createAlbum()
{
    var title = $get("tbxAlbumTitle").value;
    var visible = $get("selVisibleTo").value;
    var vMsg = $get("validMsg");
    var panel = $get("newAlbumPanel");
    
    vMsg.style.display = "none";
        
    title = trimAll(title);
    if(title == "")
    {
        vMsg.style.display = "block";
        return false;
    }
    else
    {
        if(visible == "-1")
        {
            $get("validateMsg").style.display = "inline";     
            return false;    
        }
        
        GasBuddy.PhotoService.AddAlbum(title, visible, onAddCompleted, onError);
    }
    panel.style.display = "none";
    
    var EmptyPanel = getEmptyPanel();
    if(EmptyPanel)
    {
        EmptyPanel.style.display = "none";
    }
}

function onAddCompleted(result)
{
    if(result == "-1")
    {
        alert("Oops, we'r having problem on the server.!");        
    }
    else
        goToUploadPage(result);   
}

function onError()
{
   alert("Oops, we'r having problem on the server.!");
}

function goToUploadPage(id)
{
    var url = "/photoupload.aspx?nav=my&category=personal&albumid=" + id;
    
    window.location = url;
}

//---------------------------------------
// Album Setting
//---------------------------------------
var old_title, old_visible;
var isPopupReady = false;
var isCoverSet = false;
var old_coverId = -1;
var new_coverId = -1;
function preparePopup(id, name, visible, path)
{
    $get("asForm").style.display = "none";
    $get("settingLoad").style.display = "block";
    
    $get("aIdControl").value = id;
    $get("imgPreview").src = path;
    $get("pAlbumTitle").value = name;    
    $get("pAlbumVisible").value = visible;
    
    old_title = name;
    old_visible = visible;
    
    GetThumbnails(id);
}

function setAlbumCover()
{
    isCoverSet = true;
    $get("btnAlbumCover").style.display = "none";
    $get("albumCover").style.display = "inline";
    
    if(cIndex>-1 && pics.length>0)
    {
        new_coverId = pics[cIndex].ID;        
    } 
}

function albumSettingOK(e)
{
    var id = $get("aIdControl").value;
    var path = $get("imgPreview").src;
    var title = $get("pAlbumTitle").value;
    var visible = $get("pAlbumVisible").value;
    var photoCoverId = -1;     
    
    if(isCoverSet==true)
        photoCoverId = new_coverId;
    else
        photoCoverId = old_coverId;
    
    if( parseInt(id) > 0 && (title != old_title || visible != old_visible) || (old_index != -1 && old_index != cIndex) )
    {
        GasBuddy.PhotoService.EditAlbumInfo(id, title, visible, photoCoverId, onEditCompleted);
    }
    else if(parseInt(id) < 0)
    {
        alert("Invalid ID!");
    }  
}

function onEditCompleted(result)
{
    if(result!="1")
    {
        alert("Oops, we'r having problem on the server.");  
    }
    else
    {
        showUpdateMessage("on");
        AlbumListUpdate();        
    }    
}

function showUpdateMessage(action)
{
    var updateIndicator = $get("ajax_indicator");
    if(updateIndicator)
    {
        if(action == "on")
        {        
            updateIndicator.style.display = "block";
        }
        else
        {
            updateIndicator.style.display = "none";
        }
    }
}

function deleteAlbum(id)
{
    if( confirm("Are you sure to delete this album?") )
    {
        GasBuddy.PhotoService.DeleteAlbum(id, onDeleteCompleted);
    }
    
    return false;
}

function onDeleteCompleted(result)
{
    if(result!="1")
    {
        alert("Oops, we'r having problem on the server.!");  
    }
    else
    {
        AlbumListUpdate();        
    } 
}

function checkEnterKey(evt)
{
    if(evt.keyCode == Sys.UI.Key.enter)
    {
        evt.preventDefault();
        $get("tbxAlbumTitle").focus();
    }
}

function preventEnterKey(evt)
{
    if(evt.keyCode == Sys.UI.Key.enter)
    {
        evt.preventDefault();
        showText();
        return false;
    }
}

function textareaEnterKey(evt)
{
    if($get("profile_textarea").value.length > 80 && checkKeyCode(evt.keyCode) == false)
    {
        evt.preventDefault();
        return false;
    }
}

function checkKeyCode(code)
{
    var isFound = false;
    switch(code)
    {
        case Sys.UI.Key.backspace:
            isFound = true
            break
        case Sys.UI.Key.tab:
            isFound = true
            break
        case Sys.UI.Key.esc:
            isFound = true
            break
        case Sys.UI.Key.end:
            isFound = true
            break
        case Sys.UI.Key.home:
            isFound = true
            break
        case Sys.UI.Key.left:
            isFound = true
            break
        case Sys.UI.Key.right:
            isFound = true
            break
        case Sys.UI.Key.up:
            isFound = true
            break
        case Sys.UI.Key.down:
            isFound = true
            break
        case Sys.UI.Key.del:
            isFound = true
            break
        case 16: //"Shift" key
            isFound = true
            break
    }
    return isFound;
}

function GetThumbnails(id)
{
    $get("imgIndex").innerHTML = " 0/0 ";
    GasBuddy.PhotoService.GetThumbnailList(id, onThumbnailCompleted, onError);
}

var pics;var cIndex=0; var old_index = -1;
function onThumbnailCompleted(result)
{
    $get("asForm").style.display = "block";
    $get("settingLoad").style.display = "none";
    
    if(result)
    {
        pics = result;
        if(pics.length > 0)
        {
            //find the cover picture
            for(var i=0;i<pics.length;i++)
            {
                if(pics[i].IsCover == true)
                    cIndex = i;
            }   
            //show index information
            $get("imgIndex").innerHTML = " " + (cIndex+1) + "/" + pics.length + " ";
            old_index = cIndex;
            $get("imgPreview").src = pics[cIndex].Thumbnail;
            old_coverId = pics[cIndex].ID;
        }
    }
}

// action: animation direction control
// 1: moving right
// -1: moving left
function nextImage(action)
{
    $get("btnAlbumCover").style.display = "inline";
    $get("albumCover").style.display = "none";
    
    if( $get("imgIndex").innerHTML.indexOf("0/0") == -1)
    {
        var index;
        //Moving left
        if(action == -1)
        {        
            index = parseInt(cIndex - 1);
            if(index>-1)
            {
                $get("imgPreview").src = pics[index].Thumbnail;
                cIndex = index;
            }    
        }
        //Moving right
        else
        {
            index = parseInt(cIndex + 1);
            if(index<pics.length)
            {
                $get("imgPreview").src = pics[index].Thumbnail;
                cIndex = index;
            }
        }
        //show index information
        $get("imgIndex").innerHTML = " " + (cIndex+1) + "/" + pics.length + " ";
        
        if((isCoverSet==true && pics[cIndex].ID == new_coverId) || (isCoverSet==false && pics[cIndex].ID == old_coverId))
        {
            $get("btnAlbumCover").style.display = "none";
            $get("albumCover").style.display = "inline";
        }
    }
    return false;
}

function onError(result)
{
    alert(result.message);
}

var currentId = "";
var IsInfoSaving = false;
var IsEditing = false;
var IsBirthdayEdting = false;
function ShowEdit(e)
{
    e = e || window.event;
    var target;
    if(e.target)
        target = e.target;
    else if(e.srcElement)
        target = e.srcElement;
    
    // IsEditing is to prevent textbox is force to clearup content 
    // and reposition on other location before the value is saved
    if(target && IsEditing == false && IsBirthdayEdting == false)
    {
        var textbox;        
        IsInfoSaving = false;
        IsEditing = true;
        
        currentId = target.id.substring(9);
        var bounds = Sys.UI.DomElement.getBounds(target);
        target.style.display = "none";
             
        if(currentId=="Birthday")
        {
            IsBirthdayEdting = true
            IsEditing = false;
            $get("birthdate_panel").style.display = "block";
        }
        else if(currentId != "Tips" && currentId != "Quote")
            textbox = $get("profile_text_edit");
        else if(currentId =="Quote")
            textbox = $get("profile_quote_edit");
        else
            textbox = $get("profile_textarea");       
                  
        if(textbox)
        {          
            if(getElementText(target) != "Click Here To Edit")
                textbox.value = getElementText(target);
                
            textbox.style.display = "block";
            textbox.style.left = bounds.x + "px";
            textbox.style.top = bounds.y - 2 + "px";
            textbox.focus();                
        }
        else
        {
            var birthPanel = $get("birthdate_panel");
            birthPanel.style.display = "block";
            birthPanel.style.left = bounds.x + "px";
            birthPanel.style.top = bounds.y + "px";
            loadBirthdayInfo();
        }
    }
    else
    {
        showText();
        ShowEdit();
    }
}

var old_value = "";
var new_value = "";
var contentText = ""; 
function showText()
{
    // This function response to two events, onblur and onkeydown
    // IsInfoSaving is to prevent onblur triggering saving values
    // from textbox twice    
    if(currentId.length > 1)
    {           
        $get("profile_text_edit").style.display = "none";
        $get("profile_quote_edit").style.display = "none";
        $get("profile_textarea").style.display = "none";
        $get("pro_span_" + currentId).style.display = "inline";
               
        var profileNode = $get("pro_span_" + currentId);
        
        //save old value
        if(getElementText(profileNode)!="Click Here To Edit")
            old_value = getElementText(profileNode);
        else
            old_value = "";
        
        //save textbox content to the global variable
        //before textbox is cleared up
        if(IsEditing == true)
        {
            if(currentId!="Tips" && currentId!="Quote")
                contentText = $get("profile_text_edit").value;
            else if(currentId=="Quote")
                contentText = $get("profile_quote_edit").value;
            else
                contentText = $get("profile_textarea").value;
                  
            contentText = trimAll(contentText);
            IsEditing = false;
        }
        
        if(IsInfoSaving == false)
        {        
            new_value = contentText;
           
            if(old_value!=new_value)
            {
                profileNode.innerHTML = "saving...";
                updateProfile(contentText);        
                IsInfoSaving = true;                               
                //GasBuddy_ASPX.ProfileService.UpdateProfile(currentProfile, currentId + ":" + new_value, onProfileSaved);                        
                GasBuddy.ProfileService.UpdateProfile(currentProfile, currentId + ":" + new_value, onProfileSaved);                        
            }
             
            $get("profile_text_edit").value = "";
            $get("profile_textarea").value = "";
            $get("profile_quote_edit").value = "";
        }
        
    }
}
function updateProfile(content)
{        
    if(currentId == "Hobbies") currentProfile.Hobbies = content;
    
    if(currentId == "Job") currentProfile.Job = content;
    
    if(currentId == "Education") currentProfile.Education = content;       
    
    if(currentId == "Foods") currentProfile.Foods = content;
    
    if(currentId == "TVShows") currentProfile.TVShows = content;
    
    if(currentId == "Movies") currentProfile.Movies = content;
    
    if(currentId == "Quote") currentProfile.Quote = content; 
    
    if(currentId == "Tips") currentProfile.Tips = content; 
}

function LoadProfile()
{
     $get("profile_text_edit").onblur = showText;
     $get("profile_quote_edit").onblur = showText;
     $get("profile_textarea").onblur = showText;
     $addHandler($get("profile_text_edit"), 'keydown', preventEnterKey);
     $addHandler($get("profile_textarea"), 'keydown', textareaEnterKey);
     loadData();
     generateYears();
}
function loadData()
{
    //GasBuddy_ASPX.ProfileService.GetProfile(onProfileCompleted);
    GasBuddy.ProfileService.GetProfile(onProfileCompleted);
}
var currentProfile;
function onProfileCompleted(profile)
{
    if(profile)
    {
        var target;
        currentProfile = profile;
        if(profile.Birthday && profile.Birthday != "" && profile.Birthday.indexOf("1900") == -1)
            update_birthday_span(currentProfile.Visibility, currentProfile.Birthday, "pro_span_Birthday");
        else
            update_profile_span( $get("pro_span_Birthday"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Hobbies && profile.Hobbies != "")
            update_profile_span( $get("pro_span_Hobbies"), profile.Hobbies, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Hobbies"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Job && profile.Job != "")
            update_profile_span( $get("pro_span_Job"), profile.Job, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Job"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Education && profile.Education != "")
            update_profile_span( $get("pro_span_Education"), profile.Education, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Education"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Foods && profile.Foods != "")
            update_profile_span( $get("pro_span_Foods"), profile.Foods, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Foods"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.TVShows && profile.TVShows != "")
            update_profile_span( $get("pro_span_TVShows"), profile.TVShows, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_TVShows"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Movies && profile.Movies != "")
            update_profile_span( $get("pro_span_Movies"), profile.Movies, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Movies"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Quote && profile.Quote != "")
            update_profile_span( $get("pro_span_Quote"), profile.Quote, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Quote"), "Click Here To Edit", "italic", "normal" );
            
        if(profile.Tips && profile.Tips != "")
            update_profile_span( $get("pro_span_Tips"), profile.Tips, "normal", "bold" );
        else
            update_profile_span( $get("pro_span_Tips"), "Click Here To Edit", "italic", "normal" );
    }
}
function update_profile_span(target, value, style, weight)
{
    setElementText(target, value);
    target.style.fontStyle = style;
    target.style.fontWeight = weight;
}

function update_birthday_span(visibility, birthday, id)
{
   if(birthday != "Jan 1, 1900")
   {
       var short_birthday = birthday.substring(0, birthday.indexOf(","));
       
       if(visibility == 2 || birthday.indexOf("1890") != -1)
            update_profile_span( $get(id) ,short_birthday, "normal", "bold");
        else if(visibility == 3)
            update_profile_span( $get(id) , "hide", "italic", "normal");    
        else
            update_profile_span( $get(id) , birthday, "normal", "bold"); 
   } 
   else
        update_profile_span( $get(id) , "Click Here To Edit", "italic", "normal"); 
}

function onProfileSaved(result)
{     
    if(result != "")
    {
        var cId = result.substring(0, result.indexOf(":"));        
        var content = "";
        content = result.substring(result.indexOf(":") + 1);
        
        var profileNode = $get("pro_span_" + cId);
                 
        if(content == "") 
            update_profile_span(profileNode, "Click Here To Edit", "italic", "normal");        
        else
            update_profile_span(profileNode, content, "normal", "bold");        
    }
    else
        alert("Oops, we'r having problem on the server.");
}

function generateYears()
{      
    for(i=0;i<90;i++)
    {
        var id = 2008 - i;
        element = $get(id.toString());
        var clone = element.cloneNode(true);        
        element.parentNode.appendChild(clone);
        clone.id = parseInt(id) - 1;
        clone.value = parseInt(id) - 1;
        clone.innerHTML = parseInt(id) - 1;
    }
}

function close_birth_panel()
{
    //reset controls
    $get("birthdate_panel").style.display = "none";
    $get("pick_day").options[0].selected = "selected";
    $get("pick_month").options[0].selected = "selected";
    $get("pick_year").options[0].selected = "selected";
    
    IsBirthdayEdting = false;
    var id = "pro_span_" + currentId;
    $get(id).style.display = "inline";
    if(currentProfile.Birthday.indexOf("1900") == -1)
    {
        update_birthday_span(currentProfile.Visibility, currentProfile.Birthday, id);
    }
    else
        update_profile_span( $get(id) , "Click Here To Edit", "italic", "normal");      
}
//load birthday Info onto popup panel
function loadBirthdayInfo()
{
    var birthday = currentProfile.Birthday;
    if(birthday.indexOf("1900") == -1)
    {
        var month = birthday.substring(0, 3);
        var day = birthday.substring(4, birthday.indexOf(","));
        var year = birthday.substring(birthday.indexOf(",") + 2);
        
        var month_control = $get("pick_month");
        var day_control = $get("pick_day");
        var year_control = $get("pick_year");
        setDropdown(month_control, month);
        setDropdown(day_control, day);        
        if(year.indexOf("1890") == -1) setDropdown(year_control, year);        
        setRadioButtons();
    }
}

var new_birthday;
var new_visibility;
function save_birthday()
{
    $get("birthdate_panel").style.display = "none";
    var day = $get("pick_day").options[$get("pick_day").selectedIndex].value;
    var month = $get("pick_month").options[$get("pick_month").selectedIndex].value;
    var month_long = $get("pick_month").options[$get("pick_month").selectedIndex].innerHTML;
    var year = $get("pick_year").options[$get("pick_year").selectedIndex].value;
    IsBirthdayEdting = false;
    
    var birthday = month_long + " " + day + ", " + year;
    var visibility = getVisibility();
    var id = "pro_span_" + currentId;    
    update_birthday_span(visibility, birthday, id);
    
    $get(id).style.display = "inline";
    
    //Display selected values
    if(day!= "0" && month != "00")
    {   
        //GasBuddy_ASPX.ProfileService.UpdateProfileBirthday(birthday, parseInt(visibility), onUpdateBirthdayCompleted);    
        GasBuddy.ProfileService.UpdateProfileBirthday(birthday, parseInt(visibility), onUpdateBirthdayCompleted);    
        new_birthday = birthday;
        new_visibility = visibility;
    }
    else
    {
       //No birthday is selected
       currentProfile.Birthday = "Jan 1, 1900";
       //GasBuddy_ASPX.ProfileService.UpdateProfileBirthday("Jan 1, 1900", parseInt(visibility), doNothing); 
       GasBuddy.ProfileService.UpdateProfileBirthday("Jan 1, 1900", parseInt(visibility), doNothing); 
       close_birth_panel();       
    }
}

function doNothing(result) {}

function setDropdown(control, value)
{
    for(i=0;i<control.options.length;i++)
    {
        if(control.options[i].innerHTML == value)
        {
            control.selectedIndex = i;
            return;
        }
    }
}

function setRadioButtons()
{
    var visibility = currentProfile.Visibility;
    var controls = document.getElementsByName("visibility");
    for(i=0;i<controls.length;i++)
    {
        if(controls[i].value == visibility)
            controls[i].checked = true;
    }
}

function onUpdateBirthdayCompleted(result)
{
    if(result == true)
    {
        currentProfile.Birthday = new_birthday;
        currentProfile.Visibility = new_visibility;
    }
    else
        alert("Oops, we'r having problem on the server..");
}

function getVisibility()
{
    var controls = document.getElementsByName("visibility");
    for(i=0;i<controls.length;i++)
    {
        if(controls[i].checked == true)
            return controls[i].value;
    }
    return 1;
}

