/* +---------------------------------------------------------------+
// | jamroom_javascript.inc.js - Jamroom Misc Javascript functions |
// +---------------------------------------------------------------+
// | Copyright (c) 2003-2009 by Brian Johnson <bigguy@jamroom.net> |
// +---------------------------------------------------------------+
// $Id: jamroom_javascript.inc.js,v 1.20 2010/12/22 01:06:44 kyle Exp $
*/

// If using Jamroom Cluster Server, document.domain can help with
// cross server Javascript
// document.domain = 'yourdomain.com';


/**
 * popwin() is a generic popup window creator
 */
function popwin(mypage,myname,w,h,scroll)
{
    LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
    TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
    settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable';
    win = window.open(mypage,myname,settings)
    if (win.opener == null) {
        win.opener = self;
    }
}

/**
 * lockFormSubmit() will "lock" a form so it cannot be submitted twice
 */
function lockFormSubmit(lock)
{
    $(':button').attr("disabled","disabled");
    $('input[type=submit]').attr("disabled","disabled");
}

/**
 * The move() function is used in Jamroom's "move lists" where items can be re-ordered
 */
function move(index,to) {
    var list = document.form.list;
    var total = list.options.length-1;
    if (index == -1) {
        return false;
    }
    if (to == +1 && index == total) {
        return false;
    }
    if (to == -1 && index == 0) {
        return false;
    }
    var items = new Array;
    var values = new Array;
    for (i = total; i >= 0; i--) {
        items[i] = list.options[i].text;
        values[i] = list.options[i].value;
    }
    for (i = total; i >= 0; i--) {
        if (index == i) {
            list.options[i + to] = new Option(items[i],values[i + to], 0, 1);
            list.options[i] = new Option(items[i + to], values[i]);
            i--;
        }
        else {
            list.options[i] = new Option(items[i], values[i]);
        }
    }
    list.focus();
}

/**
 * The newCaptcha() function resets the captcha image to a new image
 */
function newCaptcha(width,height,url)
{
    var now = new Date();
    $('#captcha').attr('src',url+'/image.php?mode=captcha&width='+width+'&height='+height+'&u='+ now.getTime());
    return true;
}

/**
 * The vaultpop() function is used in the flash players
 */
function vaultpop(URL)
{
    var day = new Date();
    var id  = day.getTime();
    eval("page"+ id +" = window.open(URL, '"+ id +"', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=650,height=600,left = 50,top = 50');");
}

// function jframe - used for simulating an iframe with AJAX page load
function jframe(j_div,j_url)
{
  if (window.XMLHttpRequest) {
    var xobj = new XMLHttpRequest();
  }
  else if (window.ActiveXObject) {
    var xobj = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else {
    return(false);
  }
  xobj.open("GET",j_url,true);
  xobj.onreadystatechange=function(){
    if (xobj.readyState == 4) {
      document.getElementById(j_div).innerHTML=xobj.responseText;
    }
  }
  xobj.send(null);
}

/**
 * The jrSetCookie function will set a Javascript cookie
 */
function jrSetCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = "; expires="+ date.toGMTString();
    }
    else var expires = "";
    document.cookie = name +"="+ value + expires +"; path=/";
}

/**
 * The jrReadCookie Function will return the value of a previoously set cookie
 */
function jrReadCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length); {
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

/**
 * The jrEraseCookie will remove a cookie set by jrSetCookie()
 */
function jrEraseCookie(name) {
    jrSetCookie(name,"",-1);
}

/**
 * jrEscape() function is a UTF8 safe Javascript url encoder.
 */
function jrEscape(text) {
    if (encodeURIComponent) {
        text = encodeURIComponent(text);
    }
    else {
        text = escape(text);
    }
    return text;
}

/**
 * The jrCheckFileAllowed function is used to validate that the user
 * is attempting to upload a file that is allowed in their Quota.
 *
 * @param string Form name of input=file
 * @param string Comma separated list of allowed file extensions
 */
function jrCheckFileAllowed(f_name,extensions,e_text)
{
    var f = document.form;
    for (var i=0; i < f.elements.length; i++) {
        var e = f.elements[i];
        if (e.name == f_name && e.value.length > 0) {
            var fext = e.value.split('.').pop();
            var fext = fext.toLowerCase();
            var _tmp = extensions.split(',');
            for (i = 0; i < _tmp.length ; i++) {
                if (fext == _tmp[i].toLowerCase()) {
                    return true;
                }
            }
            $('.error').removeClass('error');
            $('input[name=\''+ f_name +'\']').addClass('error');
            alert(e_text);
            return false;
        }
    }
    // Fall through means field was left empty, which is OK
    return true;
}

/**
 * The jrCheckFileRequired function will check to be sure a FILE is
 * being uploaded when required.
 *
 * @param string Form name of input=file
 * @param string Error message if field is empty
 */
function jrCheckFileRequired(f_name,e_text)
{
    var f = document.form;
    for (var i=0; i < f.elements.length; i++) {
        var e = f.elements[i];
        if (e.name == f_name && e.value.length == 0) {
            $('.error').removeClass('error');
            $('input[name=\''+ f_name +'\']').addClass('error');
            alert(e_text);
            return false;
        }
    }
    return true;
}

/**
 * The jrCheckRequired() function is a simple form validator that
 * will pass entered form values to the server via an AJAX call
 * which allows the validation to be controlled by the Form Controller.
 *
 * @param string MD5 hash for unique validation request (added by Jamroom Core automatically)
 */
function jrCheckRequired(key)
{
    u = jrFormToUrl();
    is_error = false;
    if (u.length > 0) {
        // Submit URL for validation
        $.ajax({
            type: "POST",
            async: false,
            cache: false,
            url: jamroom_url +'/index.php?mode=validate&key='+ key + u,
            success: function(data,stat,xhr) {
                if (data.indexOf('|||') != -1) {
                    var _res = data.split('|||');
                    $('.error').removeClass('error');
                    $('[name=\''+ _res[0] +'\']').addClass('error');
                    alert(_res[1]);
                    is_error = true; 
                    return true;
                }
                // Remove any existing errors
                $('.error').removeClass('error');
            },
            error: function() { return true; }  // Let server side handle
        });
    }
    if (is_error) {
        return false;
    }
    return true;
}

/**
 * The jrSleep function is a "sleep" (in milliseconds) for Javascript.
 *
 * @param int Number of milliseconds to sleep
 */
function jrSleep(ms)
{
    var start = new Date().getTime();
    while (new Date().getTime() < start + ms);
}

/**
 * The jrGrayOut function will "gray out" the screen.
 */
function jrGrayOut()
{
    $('html').css({opacity: 0.3,'width':$(document).width(),'height':$(document).height()});
}

/**
 * The jrProgressSubmit function is used to "submit" a form into a hidden
 * iframe so the "progress update" modal window can show.
 */
function jrProgressSubmit(key,f_name)
{
    lockFormSubmit(this);
    $('#jr_progress_section').modal();
    jrProgressUpdate(key);
    f_name.target = 'jr_work_frame';
    f_name.submit();
}

/**
 * The jrProgressUpdate function is used to handle the small "progress"
 * popups that theme generation and cluster transfer uses.
 *
 * @param string DB Key as set in script
 */
function jrProgressUpdate(key) {
    $('.button').attr("disabled","disabled");
    sid = setInterval(function() {
        $.ajax({
          cache: false,
          url: 'tools.php?mode=pu&k='+ key,
          success: jrProgressUpdate_success,
          error: jrProgressUpdate_error
        })
    },2000);
}
function jrProgressUpdate_success(t_data,t_status,req) {
    if (req.readyState == 4) {
        if (req.status == 200) {
            var r = t_data.split('|');
            var cnt = Number(r[0]);
            var tot = Number(r[1]);
            var err = Number(r[2]);
            $('#count').text(cnt + err);
            $('#total').text(tot);
            if (err > 0) {
                if (typeof r[3] != "undefined" && r[3].length > 0) {
                    $('#error_msg_text').text(r[3]);
                }
                else {
                    $('#error_cnt').text(err);
                }
                $('#error_msg').show(function() {
                    $('input[type=button]').removeAttr("disabled");
                });
            }
            if ((cnt + err) >= tot) {
                clearInterval(sid);
                $('#count').text(tot);
                $('#total').text(tot);
                if (typeof r[3] == "undefined" || r[3].length == 0) {
                    $('#success_msg').show();
                }
                $('input[type=button]').removeAttr("disabled");
            }
        }
    }
}
function jrProgressUpdate_error(req,textStatus,errorThrown) {
    clearInterval(sid);
    $('#error_msg').show(function() {
        $('#error_msg_text').text('An Error was encountered communicating with the server!');
    });
    $('.button').removeAttr("disabled");
}
function jrUploadProgress(tmp,slots)
{
    // First - see how many files we are uploading
    var uploading = 0;
    var _filename = [];
    for (var i = 0; i <= slots; i++) {
        if (parent.document.form.elements['upfile_' + i] && parent.document.form.elements['upfile_' + i].value != "") {
            uploading++;
            _filename[i] = parent.document.form.elements['upfile_' + i].value;
        }
    }

    // Show our progress in the form
    if (uploading > 0) {

        // Save our form in case we run into upload issues...
        frm = top.location.href +'&jrpe=1'+ jrFormToUrl();
        if (frm.length < 4000) { 
           jrSetCookie('jrProgressForm',frm,1);
        }
        // Show and display our progress bar
        $('#progress_bar',top.document).show();
        var mw = $('#upload_status',top.document).attr('title');
        // Now - every second we need to query Jamroom's progress.php
        // script to get our upload progress
        sid = setInterval(function() {
            $.ajax({
                type: "GET",
                cache: false,
                url: jamroom_url +'/progress.php?tmp='+ tmp +'&tu='+ uploading +'&mw='+ mw,
                success: jrProgressSuccess,
                error: jrProgressError
            })
        },1000);
    }
}
function jrProgressError(req,textStatus,errorThrown)
{
    alert('ERROR: '+ textStatus);
}
function jrProgressSuccess(t_data,t_status,req)
{
    if (req.readyState == 4) {
        if (req.status == 200) {
            // Check for MAX_UPLOAD_ERROR
            if (t_data == "MAX_UPLOAD_ERROR") {
                var frm = jrReadCookie('jrProgressForm');
                if (typeof frm != "undefined") {
                    jrEraseCookie('jrProgressForm'); 
                    top.location.href = frm;
                    return false;
                }
                top.location.reload(); 
                return false;
            }
            jrEraseCookie('jrProgressForm'); 
            // our TextData will come in as a pipe delimitted value:
            // 7064328|7090533|1|100|600|0|00:10|-0:00|692.43 KB|6.74 MB|6.76 MB|Converting uploaded HIFI file to proper format...
            var _num = t_data.split('|');
            // Upload is in progress and successfull - make sure progress meter
            // is displayed and updated
            if (typeof shown == "undefined" && _num[4] > 0) {
                shown = true;
            }
            if (typeof shown != "undefined" && _num[4] <= 0) {
                _num[4] = 400;
            }
            $('#upload_status',top.document).animate({width:_num[4] +'px'},1000);
            $('#total_kbytes',top.document).html(_num[9]);
            $('#current',top.document).html(_num[10]);
            $('#total_uploads',top.document).html(_num[2]);
            $('#percent',top.document).html(_num[3] +'%');
            $('#uploaded_files',top.document).html(_num[5]);
            $('#time',top.document).html(_num[6]);
            $('#remain',top.document).html(_num[7]);
            $('#speed',top.document).html(_num[8]);
            // If we have finished uploading, close (we add in
            // 5000 bytes here to account for the form size)
            if (Number(_num[1]) >= (Number(_num[0]) - 5000)) {
                // We should be at the end of our upload.  We now want to go into our
                // "processing" phase - this will let the user know the files have
                // completed uploading, but now we're going into either the converter
                // section, or we are saving the files to the server.
                $('#progress_div',top.document).remove();
                $('#con_progress',top.document).show();
                if (_num[11].length > 0) {
                    $('#pr_message',top.document).html(_num[11]);
                }
            }
        }
    }
}

/**
 * The jrFormToUrl function will parse a Jamroom form and create
 * a URL portion for use in reidrection.
 */
function jrFormToUrl()
{
    var f = top.document.form;
    var u = '';
    for (var i=0; i < f.elements.length; i++) {
        var e = f.elements[i];
        switch (e.type) {
            case 'checkbox':
                if (e.checked) {
                    var u = u +'&'+ e.name +'=on';
                }
                break;
            case 'text':
            case 'file':
            case 'radio':
            case 'select-one':
            case 'hidden':
                var u = u +'&'+ e.name +'='+ jrEscape(e.value);
                break;
            case 'textarea':
                // We could have the TinyMCE editor active, and we then
                // need to adjust the way we get out data
                if (typeof tinyMCE != "undefined") {
                    var t = tinyMCE.get(e.name);
                    if (typeof t != "undefined") {
                        var v = tinyMCE.get(e.name).getContent();
                        if (typeof v != "undefined") {
                            var u = u +'&'+ e.name +'='+ jrEscape(v);
                        }
                        else {
                            var u = u +'&'+ e.name +'='+ jrEscape(e.value);
                        }
                    }
                    else {
                        var u = u +'&'+ e.name +'='+ jrEscape(e.value);
                    }
                }
                else {
                    var u = u +'&'+ e.name +'='+ jrEscape(e.value);
                }
                var t = null; 
                var v = null; 
                break;
        }
    }
    return u;
}

