
//**************************************************************************************
//
//  tink.js is the main placeholder for javascript functions and logic
//
//**************************************************************************************


// Phase 1 implementation of sub-domains and load-balancing
//     - tink.js picks domains (configserverdomainurl, proxydomainurl/swfurl), pass them on to swfContent to retrieve swf from there and pass it on to swf to use appropriate roxy
//     - all data + php are saved/executed on master domain - in other words configserverdomainurl is always www.tinkomatic.com
function setServers() {
    
    // Ajax requests using the regular XMLHttpRequest mechanism can only be sent to a server in the same domain as the page was served from (Same Origin Policy)
    // There is a solution with ExtJS (http://extjs.com/forum/showthread.php?t=56878) - but will just stick to the same domain for now
    // BOTTOM LINE: configserverdomainurl should ALWAYS BE SET to the SERVER FROM WHICH TINK.JS IS SERVED
    // ALSO currently, the swf' url is the same as the proxy url, and in order to work craigslist needs to be proxied via yahoo
    
    // Prod config
    window.configserverdomainurl = "http://www.tinkomatic.com/";
    window.swfurl = "http://tinkomatic.com.p2.hostingprod.com/";
    
    // Demo/staging Config
    //window.configserverdomainurl = "http://www.tinkomatic.com/demo/";
    //window.swfurl = "http://tinkomatic.com.p2.hostingprod.com/";
    
    // Dev Config
    //window.configserverdomainurl = "http://www.tinkurl.com/next/";
    //window.swfurl = "http://www.tinkurl.com/next/";
}

function showFBFeedDialog(itemDescription, itemURL, itemImageURL, providerName, providerURL, promptMessage, defaultMessage) { 
    if (itemImageURL == null)
        itemImageURL = "http://tinkomatic.com/images/logo_75.gif";
    var comment_data = {"images":[{"src":itemImageURL, "href":itemURL}], 
                        "itemDescription":itemDescription,
                        "itemURL":itemURL, 
                        "providerName":providerName,
                        "providerURL":providerURL
                        };

    var defaultMsg = {"value":defaultMessage};
    var showFeedDialogResult = FB.Connect.showFeedDialog(76704860179, comment_data, null, null, null, FB.RequireConnect.promptConnect, null, promptMessage, defaultMsg); 
    return true;
}

// Reset text on input fields
function  reset_text(text, id) {
  var object;  
  object = document.getElementById(id);
  if (object.value == text)
    object.value= "";
  else if (object.value == "")
    object.value = text;
}


// Sets Cookie
function setCookie(c_name,value,expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    //alert("Set Cookie to " + c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()));
    document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + exdate.toGMTString());
}

// Retrieves Cookie
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 "";
}

//X
function setLoggedInAsGuestCookie(isLoggedInAsGuest) { 
    // isLoggedInAsGuest is supposed to be set to either 'true' or 'false'
    setCookie("keepLoggedInAsGuest",  isLoggedInAsGuest, 60);
}

//X
function isLoggedInAsGuest() {
    cookieContent = getCookie("keepLoggedInAsGuest");
    if (cookieContent != null && cookieContent != "" && cookieContent == "true") {
        return true;
    } else {
        return false;
    }
}

function setKeepLoggedInCookie(email, password) {
    setCookie("keepLoggedIn",  email + "+" + password, 60);
}
function isLoggedIn() {
    cookieContent = getCookie("keepLoggedIn");
    if (cookieContent != null && cookieContent != "") {
        return true;
    } else {
        return false;
    }
}
function getEmailFromCookie() {
    cookieContent = getCookie("keepLoggedIn");
    if (cookieContent != null && cookieContent != "") {
        return cookieContent.substring(0, cookieContent.indexOf('+'));
    } else {
        return "";
    }
}
function getPasswordFromCookie() {
    cookieContent = getCookie("keepLoggedIn");
    if (cookieContent != null && cookieContent != "") {
        return cookieContent.substring(cookieContent.indexOf('+') + 1);
    } else {
        return "";
    }
}


//X
function setAsTempLoggedIn(email, password) {
    setCookie("tempLoggedIn",  email + "+" + password, 60);
}
function resetTempLoggedIn() {
    setCookie("tempLoggedIn",  "");
}
function isTempLoggedIn() {
    cookieContent = getCookie("tempLoggedIn");
    if (cookieContent != null && cookieContent != "") {
        return true;
    } else {
        return false;
    }
}
function getTempLoggedInEmail() {
    cookieContent = getCookie("tempLoggedIn");
    if (cookieContent != null && cookieContent != "") {
        return cookieContent.substring(0, cookieContent.indexOf('+'));
    } else {
        return "";
    }
}
function getTempLoggedInPassword() {
    cookieContent = getCookie("tempLoggedIn");
    if (cookieContent != null && cookieContent != "") {
        return cookieContent.substring(cookieContent.indexOf('+') + 1);
    } else {
        return "";
    }
}



// Returns widgetconfigs - allows swf to get the widget_configs without using flashvar
//  since flashvars are limited to 64k
function getWidgetConfigs() {
    return window.widget_configs;
}


// Registers the user
// Expects registerResult and registerError DIVs
function register() {
    Ext.get('registerResult').dom.innerHTML = '';
    Ext.get('registerError').dom.innerHTML = '';
    Ext.Ajax.request({
		url: 'register-exec.php', 
		params: {email: Ext.get('register_email').dom.value},
		text: 'Registration in progress...',
        success : function(result, response) {
            res = Ext.util.JSON.decode(result.responseText);
            if (res.details != null) {
                Ext.get('registerResult').dom.innerHTML = res.details;
	            Ext.get('goBackToTink').dom.innerHTML = '<a href=".">>> Go Back To Tink</a>';
	        } else if (res.error != null) {
                Ext.get('registerError').dom.innerHTML = res.error;
            }
        }, 
        failure: function(result, response) {
            res = Ext.util.JSON.decode(result.responseText);
            if (res != null && res.error != null) {
                Ext.get('registerError').dom.innerHTML = res.error;
	        } else {
                Ext.get('registerError').dom.innerHTML = "An error has occured. Please try again later.";
            }
        }
    });

}

// Registers the user
// Expects registerResult and registerError DIVs
function recoverPassword() {
    Ext.get('recoverResult').dom.innerHTML = '';
    Ext.get('recoverError').dom.innerHTML = '';
    Ext.Ajax.request({
		url: 'sendpassword-exec.php', 
		params: {email: Ext.get('member_email').dom.value},
		text: 'Sending request...',
        success : function(result, response) {
            res = Ext.util.JSON.decode(result.responseText);
            if (res.details != null) {
                Ext.get('recoverResult').dom.innerHTML = res.details;
	            Ext.get('goBackToTink').dom.innerHTML = '<a href=".">>> Go Back To Tink</a>';
	        } else if (res.error != null) {
                Ext.get('recoverError').dom.innerHTML = res.error;
            }
        }, 
        failure: function(result, response) {
            res = Ext.util.JSON.decode(result.responseText);
            if (res != null && res.error != null) {
                Ext.get('recoverError').dom.innerHTML = res.error;
	        } else {
                Ext.get('recoverError').dom.innerHTML = "An error has occured. Please try again later.";
            }
        }
    });

}


// Login
function login() {
    Ext.Ajax.request({
        url: 'login-exec.php',
		params: {email: Ext.get('memberEmail').dom.value, password: Ext.get('memberPassword').dom.value}, 
	    success: function(response){
            result = Ext.util.JSON.decode(response.responseText);
            if (result.success) {
                window.email = Ext.get('memberEmail').dom.value;
                window.password = Ext.get('memberPassword').dom.value;
                window.user_data = result.user_data;
    	        window.widget_configs = result.widget_configs;
                // If KeepMeLoggedIn; add cookie with email
                if (Ext.get('keepLoggedIn').dom.checked) {
                    setKeepLoggedInCookie(window.email, window.password);
                } else {
                    setAsTempLoggedIn(window.email, window.password);
                }
                // Redirect or reload to index.html - which is smart enough to read the cookies and act accordingly
                window.location.href = "index.html";
            } else {
                loginError = "";
                if (result != null && result.error != null) {
                    loginError = result.error;
    	        } else {
                    loginError = "An error has occured. Please try again later.";
                }
                setCookie("keepLoggedIn", "", 60);
                if (window.location.href.indexOf("login.html") != -1)
                    Ext.get('loginError').dom.innerHTML = loginError;
                else
                    window.location.href = "login.html?" + escape(Ext.get('memberEmail').dom.value) + "&" + escape(loginError);
    	    }
	    }, 
        failure: function(result, response) {
            res = Ext.util.JSON.decode(result.responseText);
            if (window.location.href.indexOf("login.html") == -1)
                window.location.href = "login.html";
            if (res != null && res.error != null) {
                Ext.get('loginError').dom.innerHTML = res.error;
	        } else {
                Ext.get('loginError').dom.innerHTML = "An error has occured. Please try again later.";
            }
        }
    });
}



// Login Silently - allows for automatic login when cookie is set
function loginSilently() {
    Ext.Ajax.request({
        url: 'login-exec.php',
		params: {email: window.email, password: window.password}, 
	    success: function(response){
            result = Ext.util.JSON.decode(response.responseText);
            if (result.success) {
                window.user_data = result.user_data;
    	        window.widget_configs = result.widget_configs;
                // Switch UI to logged-in user
                setLoggedInUI();
            } else {
                //msg('Login Error', 'Could not log in: [' + result.responseText + ']');
                setCookie("keepLoggedIn", "", 60);
    	    }
	    }, 
	    failure: function(response){
	        if (response.responseText != null)
    	        msg('Error', response.responseText);
    	    else
    	        msg('Error', 'An error has occured. Please try again later. ' );
	    }
    });
}


// Logout
// Call logout-exec.php; delete swf's content; clear window.email; reset content to intro-register
function logout() {

// Invoking the swf to trigger saveUserConfig is not needed now that smart auto-save is implemented
// HOWEVER NOTE: that this doesn't work with some version of FF/Flash Player
// Could be a crossdomain issue - see http://www.longtailvideo.com/support/forum/JavaScript-Interaction/9063/Actionscript-error-when-using-JS-interactions
// Could be a Flash Player issue - see http://www.webdeveloper.com/forum/archive/index.php/t-95598.html
//    // Notify swf of need to save user configuration
//    if (navigator.appName.indexOf ('Microsoft') !=-1) {
//        window['tinkomatic'].saveUserConfig();
//    } else {
//        document['tinkomaticFF'].saveUserConfig();
//    }

    // Logout from server
    Ext.Ajax.request({
        url: 'logout-exec.php' 
        //,
        //success : function(result, response) {
        //    res = Ext.util.JSON.decode(result.responseText);
        //    msg('Logout', res.details);
        //}
    });

    setCookie("keepLoggedIn", "", 60);
//X
    setLoggedInAsGuestCookie('false');
    window.email = null;
    window.password = null;
    window.user_data = "";
    window.widget_configs = "";

    setLoggedOutUI();
}


// Change Password
// This function is expected to be called only from changepassword.html
function changePassword() {
    Ext.Ajax.request({
        url: 'changepassword-exec.php',
		params: {email: Ext.get('email').dom.value, password: Ext.get('oldpassword').dom.value, 
		            newpassword: Ext.get('newpassword').dom.value, newpassword2: Ext.get('newpassword2').dom.value}, 
        waitMsg: 'Connecting to server...',
	    success: function(response){
            result = Ext.util.JSON.decode(response.responseText);
            if (result.success) {
                // Reset appropriate cookie (we're always logged in order access changepassword.html)
                // So that it will be picked-up when user clicks on "Go Back To Tink" link
                email = Ext.get('email').dom.value;
                password = Ext.get('newpassword').dom.value;
                if (getEmailFromCookie() == email) {
                    setKeepLoggedInCookie(email, password);
                } else {
                    setAsTempLoggedIn(email, password);
                }
                Ext.get('changePasswordResult').dom.innerHTML = result.details;
	            Ext.get('goBackToTink').dom.innerHTML = '<a href=".">>> Go Back To Tink</a>';
            } else {
                changePasswordError = "";
                if (result != null && result.error != null) {
                    changePasswordError = result.error;
    	        } else {
                    changePasswordError = "An error has occured. Please try again later.";
                }
                Ext.get('changePasswordError').dom.innerHTML = changePasswordError;
    	    }
	    }, 
        failure: function(result, response) {
            res = Ext.util.JSON.decode(result.responseText);
            if (res != null && res.error != null) {
                Ext.get('changePasswordError').dom.innerHTML = res.error;
	        } else {
                Ext.get('changePasswordError').dom.innerHTML = "An error has occured. Please try again later.";
            }
        }
    });
}


// Returns browser app name - intended to be called by swf to know which save strategy to employ
function getBrowserType() {
    return navigator.appName;
}

