/**
 * common.js
 *
 * Common JS methods
 *
 * @author     Daniel Z
 * @copyright  2007 Comet Information Systems Ltd, All Rights Reserved.
 */

var URL_REGEXP = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

/*
 * A shortcut for document.getElementById
 */
function gebi(id) {
    return document.getElementById(id);
}

/*
 * A generic callback for AJAX failures
 */
function generalAJAXFailure(request, exception) {
    alert('exception:' + exception.message)
}

/*
 * Check for an empty or undefined string
 * @return boolean
 */
function isEmptyString(str) {
    return str == null || str == "";
}

/*
 * Reload an image
 * @param {string} id The id of the image to be refreshed
 */
function reloadImage(id) {
    var elem = gebi(id);
    var newSrc;

    //Check if the image was refreshed before
    var rndIndex = elem.src.indexOf("rnd");
    if (rndIndex > -1) {
        newSrc = elem.src.substring(0, rndIndex);
        newSrc += "rnd=" + (new Date()).getTime();
    } else if (elem.src.indexOf("?") > -1)
        newSrc = elem.src + "&rnd=" + (new Date()).getTime();
    else
        newSrc = elem.src + "?rnd=" + (new Date()).getTime();

    //Apply the new src
    elem.src = newSrc;
}

//Todo Daniel: doc
function showHide(id) {
    var elem = gebi(id);
    elem.style.display = elem.style.display == 'block' ? 'none' : 'block';
}

//Todo Daniel: doc
function getParentNode(elem) {
    if (elem.parentNode.tagName == undefined) return getParentNode(elem.parentNode);
    return elem.parentNode;
}

// Solomon

function displayElement() {
    $A(arguments).flatten().each(function(el) {
        el = $(el);
        if (el) el.style.display = '';
    });
}
function hideElement() {
    $A(arguments).flatten().each(function(el) {
        el = $(el);
        if (el) el.style.display = 'none';
    });
}

function toggleElementView() {
    $A(arguments).flatten().each(function(el) {
        el = $(el);
        if (el) {
            el.style.display = (el.style.display == "none") ? "block" : "none";
        }
    });
}

//Show & hide the menu + change his innerHTML content
function hideShowMenu(el, menu) {
    showHide(menu);
    el.blur();
    if (el.innerHTML == 'show menu') {
        el.innerHTML = 'hide menu';
        el.className = 'hideMenu';
    } else {
        el.innerHTML = 'show menu';
        el.className = 'showMenu';
    }
}


// functions manipulating the spans OnClick mechanism at the forms
var gThisInputIsFocused = null;

function blurThisInput(el, sibling, handler) {
    var val;
    if (handler) val = handler(el);
    else if (el.tagName.toLowerCase() == 'select') val = el.options[el.selectedIndex].text;
    else val = el.value;

    el.style.display = 'none';
    el.parentNode.getElementsByTagName(sibling)[0].innerHTML = val;
    el.parentNode.getElementsByTagName(sibling)[0].style.display = 'block';
    gThisInputIsFocused = null
}

function inputThis(el, sibling) {
    if (!gThisInputIsFocused) {
        el.style.display = 'none';
        el.parentNode.getElementsByTagName(sibling)[0].style.display = 'block';
        el.parentNode.getElementsByTagName(sibling)[0].focus();
        gThisInputIsFocused = true;
    }
}

//todo doc
function showSelectedImage(inputFile, imgId) {
    gebi(imgId).src = inputFile.value;
}

var IMAGE_FORM = null;
function uploadImage(fileInput, frmId) {
    var path = fileInput.value;
    var ext = path.substr(path.lastIndexOf(".") + 1);
    if (ext.toLowerCase() != "gif" && ext.toLowerCase() != "jpeg" && ext.toLowerCase() != "jpg" && ext.toLowerCase() != "png") {
        showError("upload", "Please select jpg/gif/png formats only");
        setTimeout("hideErrors('upload')", 2500);
    } else {
        //upload
        IMAGE_FORM = $(frmId);
        setLoadingStatus(IMAGE_FORM.getElementsByTagName('img')[0]);
        $('imgFrm').submit();
    }
}

function uploadImgCallback(src, oid, base, ext) {
    var img = IMAGE_FORM.getElementsByTagName('img')[0];
    var frmId = IMAGE_FORM.getElementsByClassName('nextFrm')[0].value;
    var hInputs = $(frmId).getElementsByClassName('imgData');
    img.src = src;
    $('loaderGif').style.display = "none";
    hInputs[0].name = "img_oid";
    hInputs[0].value = oid;
    hInputs[1].name = "img_base_path";
    hInputs[1].value = base;
    hInputs[2].name = "img_ext";
    hInputs[2].value = ext;
}

function setLoadingStatus(img) {
    var pos = Position.cumulativeOffset(img);
    var loader = $('loaderGif');
    loader.style.left = (pos[0] + (img.offsetWidth / 2) - 16) + "px";
    loader.style.top = (pos[1] + (img.offsetHeight / 2) - 16) + "px";
    loader.style.display = "block";
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

/*
	Todo - Daniel - use this function to switch tabs. look at blogView.html#111
    you can use this function for all the tabs we have in the site.
    Shlomi.
*/

/******************************************/
/********** SWITCH TABS MECHANISM  ********/
/******************************************/
//to use this method you need a UL tabs element, and the content should be placed inside DIVS
function switchTab(tab, className_for_chosen_tab, Content_Divs_Parent_ID) {

    var clickedTabIndex = null;

    // this var put inside an array the li's of the menu
    var tabs = tab.parentNode.getElementsByTagName('li');

    // this VAR put inside an array the div's of the tabs
    var content_Divs_Parent
    if (Content_Divs_Parent_ID)content_Divs_Parent = $(Content_Divs_Parent_ID).getElementsByClassName('aTabContentDiv');

    //hideErrors();
    // looping inside the array and amnipulating the visability of the tabs & content divs
    for (var i = 0; i < tabs.length; i++) {
        tabs[i].className = '';
        if (Content_Divs_Parent_ID) content_Divs_Parent[i].style.display = 'none';
        if (tab == tabs[i]) clickedTabIndex = i;
    }

    // setting the chosen classname for the chosen tab
    tab.className = className_for_chosen_tab;

    // setting display block for the chosen tab
    if (Content_Divs_Parent_ID)content_Divs_Parent[clickedTabIndex].style.display = 'block';

    tab.blur();
}

//todo doc
function doLogin() {

    // Username
    var username = gebi('loginUsernname').value;
    if (username.length == 0) {
        gebi("errLogin").style.display = "inline";
        gebi("errLogin").innerHTML = "Please enter a username";
        return;
    }

    // Password
    var pass = gebi('loginPass').value;
    if (pass.length == 0) {
        gebi("errLogin").innerHTML = "Please enter a password";
        gebi("errLogin").style.display = "inline";
        return;
    }

    // Remember me
    var rememberMe = gebi('loginRemember').checked;


    new Ajax.Request('/user/index/login/', {
        method:'post',
        parameters: ['user_name=', username, '&pass=', pass, '&remember=', rememberMe].join(''),
        onException:generalAJAXFailure,
        onFailure:generalAJAXFailure,
        onSuccess: function(response) {
            //Eval JSON
            var json = response.responseText.evalJSON();

            //Display appropriate message according to server's response
            switch (json.statusCode) {
                case ERRORS.SUCCESS:
                    window.location.href = "/users/" + username;
                //                    alert('Success');
                //                    gebi('headerSignIn').style.display = 'none';
                //                    gebi('headerSignOut').style.display = 'block';
                //                    gebi('loginForm').style.display = 'none';
                //
                //                    // Change header class name
                //                    gebi('headerMenu').className = 'menu loggedIn';
                //
                //                    // Show username
                //                    gebi('headerUsername').style.display = 'block';
                //                    gebi('headerUsername').innerHTML = json.displayName;
                    break;
                case ERRORS.ERROR_AUTHENTICATION:
                    gebi("errLogin").innerHTML = "Wrong username or password";
                    gebi("errLogin").style.display = "inline";
                    break;
            }
        }
    });

}


function clearErr() {
    gebi("errLogin").style.display = "none";
    gebi("forgotPassAnswer").style.display = "none";
    gebi("errForgotPass").style.display = "none";
}
//todo doc
function doLogout() {
    new Ajax.Request('/user/index/logout/', {
        method:'post',
        onException:generalAJAXFailure,
        onFailure:generalAJAXFailure,
        onSuccess: function(response) {
            //redirect to homepage
            window.location.href = "/";

            gebi('headerSignIn').style.display = 'block';
            gebi('headerSignOut').style.display = 'none';

            // Change header class name
            gebi('headerMenu').className = 'menu';

            // Show username
            gebi('headerUsername').style.display = 'none';
        }
    });
}

function showError(filedRef, msg, clsName) {
    var element = $(filedRef.element || filedRef);
    var pos = Position.cumulativeOffset(element);
    var bubble = $("errorBubble_" + element.id);
    var txt = $("errorMsg_" + element.id);
    if (clsName) {
        bubble.className = clsName;
    } else {
        bubble.className = "errorBubble";
    }
    bubble.style.left = (pos[0] + element.offsetWidth - 20) + "px";
    bubble.style.top = (pos[1] - 26) + "px";
    txt.innerHTML = msg;
    bubble.style.display = "block";
}

// hide bubble errors
function hideErrors(optionalId) {
    if (optionalId) {
        var bubble = $("errorBubble_" + optionalId);
        bubble.style.display = "none";
    } else {
        for (var key in cfv.observers) {
            var bubble = $("errorBubble_" + key);
            bubble.style.display = "none";
        }
    }
}

function validate() {
    var res = cfv.batchValidate();
    if (!res.success) {
        for (var key in res.errors) {
            if (res.errors[key] != true) {
                showError(res.errors[key][0].field, res.errors[key][0].errMsg);
            }
        }
        return false;
    } else {
        return true;
    }
}

function showhideForgotPass() {
    showHide("loginForm");
    showHide("forgotPassForm");
    clearErr();
}

function doForgotPassword() {
    var email = gebi("forgotEmail").value;
    //check theres input
    if (email.length == 0) {
        gebi("errForgotPass").innerHTML = "Please enter email";
        gebi("errForgotPass").style.display = "inline";
        return;
    }

    // check that value is formed like email address
    var validEmail = (email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != null);
    if (!validEmail) {
        gebi("errForgotPass").innerHTML = "Email is not Valid";
        gebi("errForgotPass").style.display = "inline";
        return;
    }

    new Ajax.Request('/user/index/forgotMyPassword/', {
        method:'post',
        parameters: ['email=', email].join(''),
        onException:generalAJAXFailure,
        onFailure:generalAJAXFailure,
        onSuccess: function(response) {
            //Eval JSON
            var json = response.responseText.evalJSON();
            var responseDiv = gebi("forgotPassAnswer");
            responseDiv.innerHTML = json;
            responseDiv.style.display = "inline";

            //Display appropriate message according to server's response

        }
    });
}

function isOptionSelected(obj) {
    return (obj.value != -1);
}

function getCGIValue(url, name) {
    var URL = new String(url);
    var key, value;
    var params = URL.split(new RegExp('\\?', 'g'));
    if (params.length > 0)
        params = new String(params[1]).split(new RegExp('\\&', 'g'));

    for (var i = 0; i < params.length; i++) {
        if (params[i].split(new RegExp('\\=', 'g')).length > 1) {
            key = params[i].split(new RegExp('\\=', 'g'))[0];
            value = unescape(params[i].split(new RegExp('\\=', 'g'))[1]);
            if (name == key)
                return value;
        }
    }
    return "";
}

function setMaxCharacters(textArea, maxChars) {
    textArea.value = textArea.value.substr(0, maxChars);
    var counter = gebi(textArea.id + "_counter");
    counter.innerHTML = (maxChars - textArea.value.length) + " characters left";
}

function openFlashUploader() {

}

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
    i || (i = 0);
    var length = this.length;
    if (i < 0) i = length + i;
    for (; i < length; i++)
        if (this[i] === item) return i;
    return -1;
};

function getCookie(sName) {
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if (sName == aCrumb[0])
            return unescape(aCrumb[1]);
    }

    // a cookie with the requested name does not exist
    return null;
}

function sendJoinrequest() {

    var email = gebi("sendEmail").value;
    if ((email.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i) != null)){
        new Ajax.Request('/user/index/sendJoinRequest/', {
            method:'post',
            parameters: ['email=', email].join(''),
            onException:generalAJAXFailure,
            onFailure:generalAJAXFailure,
            onSuccess: function(response) {
                gebi("sendEmail").value = "";
                showError("sendEmail", "Your request was sent", "infoBubble");
                setTimeout("hideErrors()", 3000);
            }
        });
    }else{
        showError("sendEmail", "Please enter a valid e-mail");
    }

    return false;
}
