var pageconst = {
    trailerLengthMax: 20,
    trailerLengthMin: 1
};

var myAjaxErrorMsg = new Array("Please Log In Again");

function getParameterByName(name, sz) {

    if (name.indexOf("?") === -1)
        name = "?" + name;
    //name = name.replace("[","\\\[").replace("]","\\\]");5
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(sz);
    if (results == null)
        return null;
    else
        return unescape(results[1]);
}
function getParameterByName1(name) { return getParameterByName(name, window.location.href); }

jQuery.fn.MakeIntoFields = function () {
    var arr = this.serializeArray();
    var props = {};
    $.each(arr, function (i, f) {
        props[f.name] = f.value;
    });
    return props;
};


function MakeIntoFields_sz(sz) {
    var kvLs = sz.split('&');
    var o = new Array();
    for (var kv in kvLs) {
        var kvA = kvLs[kv].split('=');
        var k = kvA[0];
        var v = kvA[1];
        o[k] = v;
    }
    return o;
};

//http://www.learningjquery.com/2007/08/clearing-form-data
$.fn.clearForm = function () {
    return this.each(function () {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input', this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

////////////////////////////////////////////////////
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {}; if (value === null) { value = ''; options.expires = -1; }
        var expires = ''; if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date; if (typeof options.expires == 'number') { date = new Date(); date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000)); } else { date = options.expires; }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : ''; var domain = options.domain ? '; domain=' + (options.domain) : ''; var secure = options.secure ? '; secure' : ''; document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } }
        return cookieValue;
    }
};

////////////////////////////////////////////////////

var detectPluginData = null;
$.cookie('gmtMinutes', (new Date).getTimezoneOffset(), { expires: 7 });

//no cookie->//if ($.cookie('gmtMinutes') == null)
if ($.cookie('hasCookie') == null) {
    $.cookie('hasCookie', 1, { expires: 7 });
} else if ($.cookie('hasCookie') == "1") {
}

if (typeof (detectUnityWebPlayer) != "undefined") {
    //$.cookie('pluginLastDate', new Date().toDateString());
    detectPluginData = {
        java: PluginDetect.getVersion("java"),
        QuickTime: PluginDetect.getVersion("QuickTime"),
        DevalVR: PluginDetect.getVersion("DevalVR"),
        Shockwave: PluginDetect.getVersion("Shockwave"),
        Flash: PluginDetect.getVersion("Flash"),
        WMP: PluginDetect.getVersion("Windows Media Player"),
        Silverlight: PluginDetect.getVersion("Silverlight"),
        VLC: PluginDetect.getVersion("VLC"),
        AdobeReader: PluginDetect.getVersion("AdobeReader"),
        PDFReader: PluginDetect.getVersion("PDFReader"),
        unity3d: detectUnityWebPlayer()
    }
	$.cookie('pluginLastDate', (new Date).toUTCString(), { expires: 7 });
    $.cookie('hasCookie', 2, { expires: 7 });
}

////////////////////////////////////////////////////
var perror;
var _gaq = _gaq || [];
perror = _gaq.push(['_setAccount', 'UA-17273758-2']);
if (detectPluginData) {
    perror = _gaq.push(['_setCustomVar', 1, 'Unity3d', (detectPluginData.unity3d ? "Yes" : "No"), 1]);
    perror = _gaq.push(['_setCustomVar', 2, 'SilverLight', (detectPluginData.Silverlight ? "Yes" : "No"), 1]);
    //perror=_gaq.push(['_setCustomVar',3, 'PlugB', JSON.stringify(detectPluginData),1]); 
}
perror = _gaq.push(['_trackPageview']);

(function () {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

////////////////////////////////////////////////////


function handleAjaxJsonResponse(data, refreshSelf) {

    if (data == null || data.status == null) {
        alert('invalid response from the server');
        return;
    }
    else if (data.status == 1) {
        alert('Invalid Request');
        return;
    }
    else if (data.status == 2) {
        if (data.redirect)
            window.location = data.redirect;
        else if (refreshSelf) {
            if (window.location != data.redirect) //do a check so we can call reload if there is a hash and its the same url
                window.location = data.redirect;
            else
                window.location.reload(true);
        }
        return true;
    }
    else if (data.status == 3) {
        if (data.redirect == null) {
            alert('Not logged in.');
        }
        else
            window.location = data.redirect;
    }
    else if (data.status == 4) {
        alert('You are banned. You are not allowed to do this operation');
    }
    else if (data.status == 5) {
        if (data.redirect == null) {
            alert('You do not have the permission required to do this.');
        }
        else
            window.location = data.redirect;
    }
    else if (data.status == 6) {
        alert('Server reported a logical error');
    }
    else if (data.status == 7) {
        alert('Server says Error: Not Implemented. If this is not a beta you may want to alert the host');
    }
    else if (data.status == 8) {
        alert('Server says Error: ' + data.html);
    }
    else {
        alert('Unknown message. status == ' + data.status);
    }
}

////////////////////////////////////////////////////

//QuickFix
(function () {
    var btn = $('.SubmitBox button');
    var b = btn.attr('disabled');
    btn.removeAttr('disabled');
    if (b) {
        $('.SubmitBox textarea').val('');
    }
} ());

$('.Submit').click(function (event) {
    $('.SubmitBox').eq(0).toggle('slow');
});

$('.SubmitBox button').click(function (event) {
    var txtbox = $('.SubmitBox textarea')
    var btn = $(this);
    txtbox.attr('readonly', true);
    btn.attr('disabled', true);
    btn.html("Submitting");

    var name = $('.SubmitBox .nickname').val();

    $.ajax({ url: "/submit", type: "POST", cache: false, dataType: "json", data: { body: txtbox.val(), nick: name },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            txtbox.removeAttr('readonly');
            btn.removeAttr('disabled');
            alert("Submitting failed, please try again shortly");
        },
        success: function (data, textStatus, XMLHttpRequest) {

            if (!handleAjaxJsonResponse(data)) {
                txtbox.removeAttr('readonly');
                btn.removeAttr('disabled');
                btn.html("Submit");
            }
            else {
				sneakyDisableKeyUp=true;
                setTimeout(function () {
                    txtbox.removeAttr('readonly');
                    btn.removeAttr('disabled');
                    txtbox.val("");
                    btn.html("Submit");
					sneakyDisableKeyUp=false;
                }, 5000);
                btn.html("Thank You");
            }
        }
    });
});




$('.YLS, .YDI, .YES, .NO').live('click', function () {
    voteType = $(this).attr('class');
    var id = $(this).closest('.post').find('.r').html();
    var obj = $(this);
    var YLSQ = $(this).hasClass('YLS') || $(this).hasClass('YDI');
    obj.attr('class', voteType + '2');
    $.ajax({ url: "/vote", type: "POST", cache: false, dataType: "json", data: { cmd: voteType, post: id },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            obj.attr('class', voteType);
        },
        success: function (data, textStatus, XMLHttpRequest) {
            if (!handleAjaxJsonResponse(data)) {
                obj.attr('class', voteType);
            }
            else {
                if (YLSQ) return;
                $('.PostList li').html(data.html);
            }
        }
    });
});

$('.remove').live('click', function () {
    var id = $(this).closest('.post').find('.r').html();
    if (!confirm('Are you sure you want to delete FMC #' + id))
        return;

    var postLi = $(this).closest('li');
    postLi.hide();

    $.ajax({ url: "/Admin", type: "POST", cache: false, dataType: "json", data: { cmd: "remove", post: id },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert('Server Error Type: ' + textStatus);
            postLi.show();
        },
        success: function (data, textStatus, XMLHttpRequest) {
            if (!handleAjaxJsonResponse(data)) {
                postLi.show();
            }
            else {
                postLi.remove();
            }
        }
    });
});


var sneakyDisableKeyUp=false;
$('.SubmitBox textarea').bind('keyup', function () {
	if(sneakyDisableKeyUp) return;
    var text = $(this).val();
    $('#charCount').html(text.length + " / (300 or 500 or 800)");
    var btn = $('.SubmitBox button');
    if (text.length > 800) {
        btn.attr('disabled', true);
    }
    else {
        btn.removeAttr('disabled');
    }
});

window.onbeforeunload = function () {
    var txtbox = $('.SubmitBox textarea').eq(0);
    var txt = txtbox.val();
    var btn = $('.SubmitBox button').eq(0).html();
    if (btn == "Thank You")
        return;
    if (btn == "Submitting")
        return "Submittal has not been completed";
    if (txt != '') {
        return "Your written text has not been submited";
    }
    return;
}

