var currentCourtroomDramasUrl = false;
var currentCourtroomDramasId = false;


function goToDigg() {

	var url = 'http://digg.com/submit?url=' + encodeURIComponent(top.location.href) + '&title=Instant+Jury%3A+the+court+of+public+opinion';
    var urlAjax = '/user/gotodigg';
    new Ajax.Request(urlAjax, 
    {
        method: 'post',
        onSuccess: function(response, json) {
            if (json.status == "ok") {
            	top.location.href = url;
            }
        }.bind(this),
        onException: function() {
        	top.location.href = url;
        }
    });
    
}


/**
 * Send ajax query remove section by id 
 *
 */
function ajaxRemover(url, id, controller) {

    this.section_id = id;
    this.controller = controller;
    new Ajax.Request(url, 
    {
        method: 'get',
        asynchronous: false,
        onSuccess: function(response, json) {
            if (json.status == "ok") {
                $(this.section_id).hide();
                this.controller.files--;
                this.controller.update();
            }
        }.bind(this),
        onException: function() {
        
            alert('Request error. Please, try latter.');
        }
    });
}

/**
 * Call remove file in server site;
 *
 */
function srvFileRemove(url, sectionId, controller) {

    if (confirm("Remove file?") == true) {
    
        new ajaxRemover(url, sectionId, controller);
    }

    return false;
}

/**
 * Smart login box
 *
 */
function showLoginBox() {
 
    $('divsearch').hide();
    $('divlogin').show();
    return false;
}

function hideLoginBox() {

    $('divlogin').hide();
    $('divsearch').show();
    return false;
}
/**
 * Load banners
 *
 */
function run_js(name)
{
    var the_div = document.getElementById(name);
    if(null!=the_div) {
        with(the_div) {
            var arr_scripts = the_div.getElementsByTagName("script");
            for(i in arr_scripts) {
                var src = arr_scripts[i].src;
                if(null!=src) {
                    var has_question = (src.indexOf('?', 1)>0 ? true : false );
                    if(0==src.length)
                        arr_scripts[i].setAttribute('src', '');
                    else
                        arr_scripts[i].setAttribute('src',
                        arr_scripts[i].src + (has_question==true ? '&' : '?') + '1=1');
                }                
            }
        }
    }
}
var bannerList = new Array();
function addBanner(bannerName, bannerPlaceId) {
    bannerList.push(Array(bannerName, bannerPlaceId));
}
function loadAllBanners() {
    for (var i = 0; i < bannerList.length; i++) {
        loadBanner(bannerList[i][0], bannerList[i][1]);
    }
}
function loadBanner(bannerName, bannerPlaceId) {

    this.bannerName = bannerName;
    this.bannerPlaceId = bannerPlaceId;
    var url = '/banner/load/name/' + bannerName;
    new Ajax.Request(url, {
        method: 'get',
        onSuccess: function(response, json) {            
            // prototype insert dose non work :-(
            //$(this.bannerPlaceId).insert(response.responseText);
            $(this.bannerPlaceId).innerHTML = response.responseText;
            run_js(this.bannerPlaceId);
        }.bind(this)
    });
}

function killCurrentLinks() {
    
    var a = document.getElementsByTagName('a');
    for (var i = 0; i <  a.length; i++) {
        if (a[i].href == window.self.location) {
            if ((a[i].href.indexOf('jury/vote/case') == -1) && !(a[i].id)) { // if <a.id> is not empty
            
                a[i].style.textTransform = 'uppercase';
                a[i].style.color = "#000000";    
                a[i].style.textDecoration = "none";
                a[i].onclick = function() { return false; }
            }
        }
    }
}

Event.observe(window, 'load', 
    function(event) {   
        loadAllBanners();
        killCurrentLinks();
    }
);
/**
 * COURTROOM DRAMAS Ajax loader
 *
 */
function courtroomDramasLoader(url, isNext, _blockID) {
    
    if (isNext) url += '/next/true';
    this.blockID = _blockID ? _blockID : 'dynCourtroomDramas';

    new Ajax.Request(url,
    {
        method: 'get',        
        onSuccess: function(response, json) {
            
            if (json.status == "ok") {
                
                this.json = json;
                this.response = response;
                
                if (!this.json.isNewCases) return;
                
                // Fade out
                new fade(100, -5, this.blockID, function() {
                
                    $(this.blockID).innerHTML = this.response.responseText;
                    if (this.json.caseList) {                        
                        for (var i = 0; i < this.json.caseList.length; i++) 
                            this.json.caseList[i] = 'courtroomDramas_casesPreview_' + this.json.caseList[i];
                        vallignDourtRoomDramas(this.json.caseList);
                    }
                    new fade(0, +5, this.blockID);
                    }.bind(this)
                );
            }
        }.bind(this),
        onException: function(response) {
            // Debug only:
            // trace(response);
            // alert('Request error. Please, try latter.');
        }
    });
}

function fade(start, delta, objectId, callBack) {
    
    this.start = start;
    this.delta = delta;
    this.objectId = objectId;
    this.callBack = callBack;

    new PeriodicalExecuter(function(pe) {
        if (((this.delta < 0) && (this.start <= 0)) ||
            ((this.delta > 0) && (this.start >= 100))) {
                
                pe.stop(); 
                if (this.callBack) return this.callBack();
        }
        this.start += this.delta;
        $(this.objectId).setOpacity(this.start / 100);
    }.bind(this), 0.001);
}

/**
 * COURTROOM DRAMAS periodical updator
 *
 */
function courtroomDramasPeriodical() {

    /*new PeriodicalExecuter(
        function(pe) {
            new courtroomDramasLoader(currentCourtroomDramasUrl, true);
        },
        10
    )*/
}

Event.observe(window, 'load', 
    function(event) {   
        courtroomDramasPeriodical();
    }
);


/**
 * Fill COURTROOM DRAMAS blocks in height
 * 30 - is not magic number. it's block padding . it's dependent main.css. see gradBlock.tpl
 *
 */
function vallignDourtRoomDramas(list) {

    if (list) {
        
        for (var i = 0; i < list.length; i++) {
            
            var current = $(list[i]);
            if (!current) continue;
            var parent = current.up(0);
            $(list[i] + '_guide').height = parent.getHeight() - 30;
        }
    }
}

/**
 * Dynamic Field
 *
 */
function dynField(id, baseValue) {

    this.baseValue = baseValue;
    this.isUserValue = false;
    this.object = $(id);
    if(this.object.getValue()) {
        this.isUserValue = true;
    } else {
        this.object.value = this.baseValue; 
    }
    this.object.owner = this;    
    
    this.object.onfocus = function() {

        if (this.owner.isUserValue == false) {
            this.value = "";
            this.owner.isUserValue = true;
        }
    }

    this.object.onblur = function() {
        if (this.value == '') {
            this.value = this.owner.baseValue;
            this.owner.isUserValue = false;
        } 
    }
}

function searchBox(id) {

    this.field = dynField(id, 'Enter Case #, User, Tag...');
    this.form = $("searchForm");
    form.onsubmit = function() {
        var haveSearchValue = !(parent.object.owner.isUserValue == false || parent.object.value == '');
        var haveCategory = $('search_ij_cc_id').value != '';
        if ((!haveSearchValue) && (!haveCategory)) {
            return false;
        } 
        if (!haveSearchValue) {
            $('searchBox').value = '';
        }
        return true;
    }
}


function checkVoiteForm(form) {

    var u1 = form.elements['vote[winner]'][0];
    var u2 = form.elements['vote[winner]'][1];

    if (!(u1.checked || u2.checked)) {
        
        alert('Please, select Winner');
        return false;
    }
    var winner = u1.checked ? u1 : u2;

    return confirm("Please confirm you are voting for " + winner.title + "?");
}

function AgeSelector(idMinAge, idMaxAge, minAgeList, maxAgeList) {

    this.minAgeList = minAgeList;
    this.maxAgeList = maxAgeList;
    
    this.minAge = $(idMinAge);
    this.minAge.owner = this;
    this.maxAge = $(idMaxAge);
    this.maxAge.owner = this;

    this.minAge.setFrom = this.maxAge.setFrom = function(list) {
        
        var len = this.options.length;
        for (var i = 1; i < len; i++) this.removeChild(this.options[1]);
        for (var i = 0; i < list.length; i++) {
            var opt = document.createElement("OPTION");
            opt.text = list[i];
            opt.value = i;
            this.options.add(opt);
        }
    }

    this.minAge.selectValue = this.maxAge.selectValue = function(val) {
        
        for (var i = 0; i < this.options.length; i++) {
            if (this.options[i].value == val) {
                this.selectedIndex = i;
                break;
            }
        }
    }

    this.minAge.onchange = function() {

        var val = this.owner.maxAge.value;
        this.owner.maxAge.setFrom(this.owner.maxAgeList);
        if (this.selectedIndex != 0) {
            var idx = this.selectedIndex;
            for (var i = 1; i <= idx; i++) {
                this.owner.maxAge.removeChild(this.owner.maxAge.options[1]);
            }            
        }
        this.owner.maxAge.selectValue(val);
    }
    
    this.maxAge.onchange = function() {

        var val = this.owner.minAge.value;
        this.owner.minAge.setFrom(this.owner.minAgeList);
        if (this.selectedIndex != 0) {
            var idx = this.selectedIndex;
            for (var i = this.owner.minAge.length - 1; i > idx; i--) {
                this.owner.minAge.removeChild(this.owner.minAge.options[this.owner.minAge.length - 1]);
            }
            this.owner.minAge.selectValue(val);
        }
    }
}

function drawCation(caption, id) {
    
    var w = 740;
    var h = 35;
    var src = 'images/caption.swf';
    caption = caption.toUpperCase();
    document.write('<div class="flashCaption"><div>');
    document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0" width="' + w + 
                   '" height="' + h +
                   '" id="' + id +                 
                   '" align="middle"><param name="allowScriptAccess" value="always" /><param name="movie" value="' + 
                   src + '" /><param name="quality" value="high" /><param name="FlashVars" value="caption=' + caption + '" /><param name="wmode" value="transparent" /><embed src="' + src + '" quality="high" wmode="transparent" width="' + w + '" height="' + h +'" name="' + id + '" align="middle" allowScriptAccess="always" FlashVars="caption=' + caption + '" types="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>');
    document.write('</div></div>');
}

function confirmGuilt() {
    return confirm('Are you sure you want to admit guilt in this case? This cannot be undone.');
}

function textBoxWithCounter(id, _maxCount) {

    obj = $(id);
    obj.maxCount = _maxCount;
    obj.onkeypress = function() {
        if (this.value.length >= this.maxCount) {

            this.style.cursor = 'not-allowed';
            return false;
        }
        this.style.cursor = 'auto';
        return true;
    }
    obj.onkeyup = function() {

        var notUse = this.maxCount - this.value.length;
        notUse = notUse > 0 ? notUse : 0;
        return true;
    }
}

function wshow(url, width, height) {

    if (!width) width = 900;
    if (!height) height = 600;
    posLeft = ((screen.width - width) / 2);
    posTop = ((screen.height - height) / 2);
    window.open(url, (winCol++), 
                'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=' 
                + width + 
                ',height=' + height + 
                ',left=' + posLeft + 
                ',top=' + posTop);
    return false;
}

function waitAndClose(wait) {

    new PeriodicalExecuter(function(pe) {    
        window.close();
    }, wait);
}


// search category click
function categoryClick(id) {

    $('search\[ij_cc_id\]').value=id;
    $('search\[query\]').value='';
    $('searchFormId').submit();
    return false;
}


function focusPassword() {

    $('pass_1_b').hide();
    $('pass_2_b').show();
    $('pass_2').focus();
}

function blurPassword() {

    if ($('pass_2').value == '') { 
    
        $('pass_2_b').hide();
        $('pass_1_b').show();
    }
}




// Grand Juries functions
function gjSetPeriodical() {

    if (totalGrandJuryListCount > 1) {
    
        new PeriodicalExecuter(function (pe) { gjSetActiveList(1); }, 10);
    }
}

function gjSetActiveList(num) {

    var curList = activeGrandJuryList + num;
    if (curList < 1) { curList = totalGrandJuryListCount; }
    if (curList > totalGrandJuryListCount) { curList = 1; }

    new fade(100, -5, 'gj_'+activeGrandJuryList, function() {
    
        $('gj_'+activeGrandJuryList).hide();
        activeGrandJuryList = curList;
        $('gj_'+curList).setOpacity(0);
        $('gj_'+curList).show();
        new fade(0, +5, 'gj_'+curList);
        }
    );
}
// / Grand Juries functions


// equal height to list of blocks
function equalHeight(list) {

    if (!list) { return; }

    maxHeight = 0;

    for (var i = 0; i < list.length; i++) {
        
        var current = $(list[i]);
        if (!current) continue;
        if (current.getHeight() > maxHeight) { maxHeight = current.getHeight(); }
    }

    for (var i = 0; i < list.length; i++) {
        
        if ($(list[i]+"_s")) { $(list[i]+'_s').height = maxHeight; }
    }
}



// alert checkBoxes click
function clickAlertCheckbox(cb) {

    if (cb.id == 'alert[general_1]' || cb.id == 'alert[general_2]') { // general CheckBox checked
    
        $$('input[id^="alert\["]').each(function (n) { n.checked = cb.checked; });

    } else { // simple CheckBox checked

        if ($$('input[id^="alert\[cb_"]:checked').size() == $$('input[id^="alert\[cb_"]').size()) {
        
            $('alert[general_1]').checked = $('alert[general_2]').checked = true;
        } else { $('alert[general_1]').checked = $('alert[general_2]').checked = false; }
    }
}

// submit alert checkBoxes
function submitAlertCheckbox() {
    
    if ($$('input[id^="alert\[cb_"]:checked').size() > 0) { $('alertList').submit();  }
    else { alert('Select any checkboxes!'); }
    
    return false;
}