function stub()
{
    return;
}
$(document).ready(function()
{
    anchor.init()
});

function bannerView(id)
{
    if(typeof(id) == "undefined")
    {
        id=0;
    }
    $.post('ajax/view_ad/',{video_id: id, ad_type: 3});
}
    
anchor = {
    init : function()  {
        $("a.anchorLink").click(function () { 
            elementClick = $(this).attr("href")
            destination = $(elementClick).offset().top;
            $("html:not(:animated),body:not(:animated)").animate({ 
                scrollTop: destination
            }, 'fast' );
            return false;
        })
    }
};


var is_ie = (/msie/i.test(navigator.userAgent) &&
    !/opera/i.test(navigator.userAgent));

var is_ie5 = (is_ie && /msie 5\.0/i.test(navigator.userAgent));
var is_ie7 = (is_ie && /msie 7\.0/i.test(navigator.userAgent));

/// detect Opera browser
var is_opera = /opera/i.test(navigator.userAgent);

/// detect KHTML-based browsers
var is_khtml = /Konqueror|Safari|KHTML/i.test(navigator.userAgent);

function mailFeatured (id)
{
    $.post(
        'ajax/mailfeatured/', 
        {
            mail_video_id: id
        },
        function (msg) {
            alert(msg.message)
        }, 
        "json"
        );
}

function thumbsPlayer(player_id, file, slowseek)
{
    var flashvars = {
        file: file,
        autostart: "false",
        lights: "false",
        slowseek: slowseek,
        fastseek: "2"
    };

    var params = {
        allowScriptAccess: "always",
        scale: 'noscale',
        allowFullScreen: 'true',
        wmode: "opaque"
    };

    var attributes = {
        id:player_id + "_player"
    };

    swfobject.embedSWF("/design/flash/player4thumbs.swf", player_id + '_del', "920", "518", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}


function miuPlayer(id, link)
{
    var flashvars = {
        topbar: 'false',
        link: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noBorder',
        allowFullScreen: 'true',
        bgcolor: "#ffffff",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };

    swfobject.embedSWF("packages/community/design/custom/miu/nav.swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}

function gpsffPlayer(id)
{
    var flashvars = {
        
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noBorder',
        allowFullScreen: 'true',
        bgcolor: "#ffffff",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };

    swfobject.embedSWF("packages/community/design/custom/gpsff/gpsff.swf", id + '_del', "100%", "150", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}
/*
				var so = new SWFObject("packages/community/design/custom/gpsff/gpsff.swf", "gpsff_banner", "100%", "150", "9","#ffffff");
				so.addParam("allowFullScreen", "true");
				so.addParam("allowScriptAccess", "sameDomain");
				so.write("gpsff_banner");
*/
function previewPlayer(id, link)
{
    var flashvars = {
        topbar: 'false',
        file: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };

    swfobject.embedSWF("/design/flash/preview_player.swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}
function lgPlayer(id)
{

    var params = {
        menu: "false",
        allowScriptAccess: "always",
        scale: 'noscale',
        bgcolor: "#000000"
    };
    var attributes = {
        id:id + '_lg'
    };

    swfobject.embedSWF("/design/flash/LG.swf", id + '_del', "661", "372", "9.0.0", "/design/flash/expressInstall.swf", {}, params, attributes);
}
function embedPlayer(id, link)
{
    var flashvars = {
        //fullplaylist:'false',
        playlist: 'true',
        hplaylist: 'true',
        topbar: 'false',
        file: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "always",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };

    swfobject.embedSWF("/design/flash/player.swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}


function insertVideoBanner(id, link)
{
    var flashvars = {
        link: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("/design/flash/bannerVideos.swf", id + '_del', "100%", "284", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}

function insertPromoPlayer(id)
{
    var flashvars = {
        autostart: 'false',
        embed: 'true',
        menu: 'false',
        captions: 'false',
        fullscreen: 'false',
        scalebar: '85',
        linkfromdisplay: 'false',
        topbar: 'false',
        link: "player/promo/"
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("flvplayer5.swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}


function insertCreatorsPlayer(id, arrowLink, link)
{
    var flashvars = {
        autostart: 'false',
        reload_on_video_click: 'true',
        hplaylist:  'true',
        topbar: 'false',
        arrowLink: arrowLink,
	playlist: 'false',
	repeat: 'list',
        file: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "always",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("/design/flash/player.swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}


function insertCreatorsBanner(id, type)
{
    var bannerName = 'Index';
    if(type == 3)
    {
        bannerName = 'Shows';
    }

    if(type==4)
    {
        var flashvars = {
            show: '0',
            xmlpath: 'contests_banner_data/?%26type=' + type
        };
    } 
    else
    {
        var flashvars = {
            show: '0',
            xmlpath: 'banner_data/?%26type=' + type
        };
    }
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("/design/flash/banner" + bannerName + ".swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}

function insertContestsBanner(id, type, active)
{
    var bannerName = 'Contests';

    if(type==4)
    {
        var flashvars = {
            show: '0',
            active_id: active,
            xmlpath: 'contests_banner_data/?%26type=' + type
        };
    }

    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("/design/flash/banner" + bannerName + ".swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}


function insertVideoBanner(id, link)
{
    var flashvars = {
        link: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        //allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("/design/flash/bannerVideos.swf", id + '_del', "100%", "284", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}

function insertPlaylistPlayer(id, link)
{
    var flashvars = {
        autostart: 'false',
        file: link,
        hplaylist: 'true',
        topbar: 'false',
        playlist: 'false',
        reload_on_video_click: 'true'
    };
    var params = {
        menu: "false",
        allowScriptAccess: "sameDomain",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };
    swfobject.embedSWF("/design/flash/player.swf", id + '_del', "100%", "100%", "9.0.0", "/design/flash/expressInstall.swf", flashvars, params, attributes);
}


var Cache = new Object();
function get(id)
{
    return (Cache[id]) ? Cache[id] : Cache[id] = document.getElementById(id);
}

function trim(str)
{
    var str = str.replace(/^\s\s*/, ''), ws = /\s/, i = str.length;
    while (ws.test(str.charAt(--i)))
        ;
    return str.slice(0, i + 1);
}

function findPos(obj)
{
    var curleft = curtop = 0;
    if (obj.offsetParent)
    {
        do
        {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return [curleft, curtop];
}



/* image scroll { */

function scrollMovies(container_id, direction)
{
    var container_el = document.getElementById(container_id);
    var els = new Array();
    var class_name = '';
    var first = -1;
    var last = -1;
    var el = container_el.firstChild;
    while (el)
    {
        if (el.nodeName.toLowerCase() == 'div')
        {
            els.push(el);
            if (el.className != 'hidden')
            {
                if (class_name == '')
                    class_name = el.className;
                if (first == -1)
                    first = els.length - 1;
                last = els.length - 1;
            }
        }
        el = el.nextSibling;
    }
    while (els.length % direction != 0 && direction > 0)
    {
        var theDiv = document.createElement('div');
        container_el.insertBefore(theDiv, els[els.length - 1].nextSibling);
        els.push(theDiv);
    }
    if (first + direction < 0 || last + direction > (els.length - 1))
    {
        return;
    }
    first += direction;
    last += direction;
    for (var i = 0; i < els.length; i++)
    {
        if (i >= first && i <= last)
        {
            els[i].className = class_name;
        }
        else
        {
            els[i].className = 'hidden';
        }
    }
    document.getElementById(container_id + '_counter').firstChild.nodeValue = (Math.ceil(last / Math.abs(direction))).toString();
}

function startRoll(targetId)
{
    targetId.timer = setInterval(function(arg)
    {
        return function()
        {
            roll(arg);
        }
    }(targetId), 500);
}

function roll(targetId)
{
    var item_els = targetId.getElementsByTagName('img');
    for (var i = 0; i < item_els.length; i++)
    {
        var item_el = item_els[i];
        if (item_el.className != 'hidden')
        {
            hidden = item_el;
            hidden.className = 'hidden';
            current = (item_els[i + 1]) ? item_els[i + 1]: item_els[0];
            current.className = '';
            break;
        }
    }
/*
	var item_el = targetId.firstChild;
	while (item_el)
	{
		if (item_el.nodeName.toLowerCase() == "img")
		{
			if (item_el.className != 'hidden')
			{
				hidden = item_el;
				hidden.className = 'hidden';
				current = (hidden.nextSibling) ? hidden.nextSibling : targetId.firstChild;
				current = (current.nodeType == 1) ? current : current.nextSibling;
				if (!current)
				{
					current = targetId.firstChild;
					current = (current.nodeType == 1) ? current : current.nextSibling;
				}
				current.className = '';
				break;
			}
		}
		item_el = item_el.nextSibling;
	}*/
}

function stopRoll(targetId)
{
    clearInterval(targetId.timer);
}

/* } image roll */


function insertFlash(container_id, flash_name, flash_id, width, height)
{
    var container_el = document.getElementById(container_id);

    container_el.innerHTML = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000'" +
    "codebase='http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' width='" +
    width.toString() +
    "' height='" +
    height.toString() +
    "' id='" +
    flash_id +
    "'>" +
    "<param name='allowScriptAccess' value='sameDomain' />" +
    "<param name='movie' value='" +
    flash_name +
    "' />" +
    "<param name='quality' value='high' />" +
    "<param name='bgcolor' value='#ffffff' />" +
    "<param name='wmode' value='transparent' />" +
    "<embed src='" +
    flash_name +
    "' quality='high' wmode='transparent' bgcolor='#ffffff' width='" +
    width.toString() +
    "' height='" +
    height.toString() +
    "'" +
    "name='" +
    flash_id +
    "' align='middle' allowScriptAccess='sameDomain'" +
    "type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
    "</object>";
}

function insertFlashPlayer(container_id, src, width, height)
{
    var container_el = document.getElementById(container_id);
    var str = "<object classid='clsid:d27cdb6e-ae6d-11cf-96b8-444553540000' " +
    "codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0' " +
    "width='" +
    width.toString() +
    "' height='" +
    height.toString() +
    "' id='flvplayer5' align='middle'>" +
    "<param name='allowScriptAccess' value='sameDomain' />" +
    "<param name='allowFullScreen' value='true' />" +
    "<param name='movie' value='" +
    src +
    "'/>" + //+flvplayer5.swf?xmlsource=
    //"<param name='xmlsource' value='" + xmlsource + "' />"
    "<param name='quality' value='high' />" +
    "<param name='scale' value='noscale' />" +
    "<param name='wmode' value='opaque' />" +
    "<param name='devicefont' value='true' />" +
    "<param name='bgcolor' value='#999999' />" +
    "<embed src='" +
    src +
    "' quality='high' scale='noscale' wmode='opaque' devicefont='true'    bgcolor='#999999' " +
    "width='" +
    width.toString() +
    "' height='" +
    height.toString() +
    "'    name='flvplayer5' align='middle' " +
    "allowScriptAccess='sameDomain' allowFullScreen='true' type='application/x-shockwave-flash' " +
    "pluginspage='http://www.macromedia.com/go/getflashplayer' />" +
    "</object>";// alert(xmlsource.toString());
    container_el.innerHTML = str;
}

function fixItem(target_item_el, class_name)
{
    if (class_name == null)
        class_name = "";
    var parent_el = target_item_el.parentNode;

    var item_el = parent_el.firstChild;
    while (item_el)
    {
        if (item_el.nodeName.toLowerCase() == "li")
        {
            item_el.className = class_name;
            if (item_el == target_item_el)
            {
                item_el.className = "current";
            }

        }
        item_el = item_el.nextSibling;
    }

}

function toggleList(targetId)
{
    var nxbr = targetId.nextSibling;
    while (nxbr.nodeType != 1)
    {
        nxbr = nxbr.nextSibling;
    }
    nxbr.className = (nxbr.className == 'current') ? 'hidden' : 'current';
}

function toggleList2(targetId)
{
    var listEl = document.getElementById(targetId);
    listEl.className = (listEl.className == 'current') ? 'hidden' : 'current';
}

function selectItem(id, service_name)
{
    var sval = new Array('');
    var qr = document.getElementById('query');
    var query_s = (id.firstChild.nodeType == 1) ? id.firstChild.firstChild.nodeValue : id.childNodes[1].firstChild.nodeValue;
    with (id.parentNode)
    {
        for (i = 0; i < childNodes.length; i++)
        {
            if (childNodes[i].nodeName.toLowerCase() == 'li')
            {
                sdata = (childNodes[i].firstChild.nodeType == 1) ? childNodes[i].firstChild.firstChild.nodeValue : childNodes[i].childNodes[1].firstChild.nodeValue;
                sval.push(sdata);
            }
        }
        }
    for (i = 0; i < sval.length; i++)
    {
        if (qr.value == sval[i])
        {
            qr.value = query_s;
            break;
        }
    }

    //document.getElementById('service_search').value = service_name;

    var prbr = id.parentNode.previousSibling;
    while (prbr.nodeType != 1)
    {
        prbr = prbr.previousSibling;
    }
    toggleList(prbr);
}

function cancelBubble1(event)
{
    if (window.event)
    {
        window.event.cancelBubble = true;
    }
    else
    {
        event.cancelBubble = true;
        event.preventDefault();
    }
}

function showSubcategories2(category_id)
{
    var target_item_el = document.getElementById(category_id);
    fixItem(target_item_el, 'hidden');
}

/* categories menu { */

function showSubcategories(category_id)
{
    var target_item_el = document.getElementById(category_id);
    var class_name = "sub hidden";
    var parent_el = target_item_el.parentNode.parentNode;
    var item_el = parent_el.firstChild;
    while (item_el)
    {
        if (item_el.nodeName.toLowerCase() == "li")
        {
            var sub_el = item_el.firstChild;
            while (sub_el)
            {
                if (sub_el.nodeName.toLowerCase() == "ul")
                {
                    sub_el.className = class_name;
                    if (sub_el == target_item_el)
                    {
                        sub_el.className = "sub";
                    }
                }
                sub_el = sub_el.nextSibling;
            }
        }
        item_el = item_el.nextSibling;
    }
}

/* } categories menu */
/* upload { */

//categories list
function flipCategoryType(idType)
{
    var catType = (idType == 1) ? 'cat_animation' : 'cat_video';
    var target_el = document.getElementById(catType);
    with (target_el.parentNode)
    {
        for (i = 0; i < childNodes.length; i++)
        {
            if (childNodes[i].nodeName.toLowerCase() == 'div')
            {
                childNodes[i].className = 'hidden';
                if (childNodes[i] == target_el)
                {
                    childNodes[i].className = 'current';
                }
            }
        }
        }
    var input_el = target_el.getElementsByTagName('input');
    for (var i = 0; i < input_el.length; i++)
    {
        input_el[i].checked = false;
    }
}

//popups
function openPopUp(url)
{
    newwindow = window.open(url, 'name', 'height=600,width=800,scrollbars=yes');
    /*    if ( window.focus )
	 {
	 newwindow.focus();
	 }*/
    return false;
}

function getElementsByClass(searchClass, domNode, tagName)
{
    if (domNode == null)
        domNode = document;
    if (tagName == null)
        tagName = '*';
    var el = new Array();
    var tags = domNode.getElementsByTagName(tagName);
    var tcl = ' ' + searchClass + ' ';
    for (i = 0, j = 0; i < tags.length; i++)
    {
        var test = ' ' + tags[i].className + ' ';
        if (test.indexOf(tcl) != -1)
        {
            el[j++] = tags[i];
        }
    }
    return el;
}

function toggleEll(ellId, fixId, fixClass)
{
    var ell = document.getElementById(ellId);
    ell.className = (ell.className.indexOf('hidden') != -1) ? ell.className.substr(0, ell.className.indexOf('hidden')) : ell.className + ' hidden';
    if (fixId && fixClass)
    {
        fixId.className = (fixId.className == fixClass + '1') ? fixClass + '2' : fixClass + '1';
    }
}

/*function checkSearchForm(el)
 {
 search_str_el = document.getElementById('query');
 if (search_str_el.value == '' || /^\s*$/.test(search_str_el.value) || search_str_el.value == i18n['m0016'] || search_str_el.value == i18n['m0017'] || search_str_el.value == i18n['m1470'])
 {
 showAlert(i18n['m1419']); //You should specify search criteria.
 return false;
 }

 else if (search_str_el.value.length < 3)
 {
 alert('Search term cannot be less than 3 characters.');
 return false;
 }
 return true;
 }*/
function x_window(imgSrc)
{
    margin = 20;
    x_win = open("", "thumbnails", "resizable,width=100,height=100,top=0,left=0");
    img = new Image();
    img.onload = function()
    {
        x_win.resizeTo(w = img.width + margin, h = img.height + margin * 3);
        x_win.moveTo((document.body.clientWidth - w) / 2, (document.body.clientHeight - h) / 2);
        if (img.outerHTML)
            x_win.document.write(img.outerHTML);
        else
            x_win.document.body.appendChild(img);
    }
    img.src = imgSrc;
}

function OpenImagePopup(imgPath, title, alt, width, height)
{
    if (title == undefined)
        title = 'thumbnails';
    if (alt == undefined)
        alt = 'thumbnails';
    if (width == undefined)
        width = 0;
    if (height == undefined)
        height = 0;

    var win = window.open('', 'preview', 'width=' + width + ',height=' + height + ',left=0,top=0,screenX=24,screenY=24,resizable=0,scrollbar=0,status=0,location=no');

    var winDoc = win.document;

    var content = '<img style="position:absolute;top:0;left:0;" alt="' + alt + '" id="image" src="' + imgPath + '" />'
    win.document.write(content);

    //winDoc.body.onload = function()
    var imageObj = winDoc.getElementById('image');
    imageObj.onload = function()
    {   
        var obj = winDoc.getElementById('image');
        var w = obj.width, h = obj.height;
        var iHeight = document.body.clientHeight, iWidth = self.innerWidth;

        var left = (self.opera ? iWidth : screen.availWidth) / 2 - w / 2;
        var top = (self.opera ? iHeight : screen.availHeight) / 2 - h / 2;
        win.resizeTo(w + 5, h + 28);
        win.moveTo(left, top);
    }

    win.onload = imageObj.onload;
    win.document.close();
    win.focus();
}

function sendHTTPRequest(url, callback_function, callback_parameters, post_params)
{
    var xml_http = null;
    if (typeof ActiveXObject != 'undefined')
    {
        xml_http = new ActiveXObject('Msxml2.XMLHTTP');//('Microsoft.XMLHTTP');
    }
    else
    if (typeof XMLHttpRequest != 'undefined')
    {
        xml_http = new XMLHttpRequest();
        if (xml_http.overrideMimeType)
        {
            xml_http.overrideMimeType('text/xml');
        }
    }

    if (!xml_http)
    {
        alert('Не возможно создать объект XMLHTTPRequrest');
        return;
    }
    //alert(xml_http.responseXML);
    // open document for further output
    //myWin.document.writeln(url);
    //myWin.document.close();
    //alert(url);


    xml_http.onreadystatechange = function()
    {
        //alert(xml_http.readyState);
        switch (xml_http.readyState)
        {
            //case 0: alert(0); break;
            //case 1: alert(1); break;
            //case 2: alert(2); break;
            //case 3: alert(3); break;
            case 4:
                callback_function(xml_http, callback_parameters);
                break;
        }
    }

    //  именно в таком порядке, потому что после перезагрузки не всегда срабатывает
    //  назначение для onreadystatechange в ie
    if (post_params == null)
    {
        xml_http.open('GET', url, true);
        xml_http.setRequestHeader("Content-Type", "application/xml;charset=UTF-8");
        xml_http.send(null);
    }
    else
    {
        xml_http.open('POST', url, true);
        xml_http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xml_http.setRequestHeader("Content-length", post_params.length);
        xml_http.send(post_params);
    }
}

function sendFeedback()
{
    if (document.getElementById('fb_feedback').value.toString().replace(/^\s\s*/, '').replace(/\s\s*$/, '') != '')
    {
        var user_name_el = document.getElementById('fb_user_name');
        var email_el = document.getElementById('fb_email');
        var feedback_el = document.getElementById('fb_feedback');
        var feedback_type_id_el = document.getElementById('fb_feedback_type_id');
        var url_el = document.getElementById('fb_url');

        var post_params = 'service=feedbacks&user_name=' + user_name_el.value +
        '&email=' +
        email_el.value +
        '&feedback=' +
        encodeURIComponent(feedback_el.value) +
        '&feedback_type_id=' +
        feedback_type_id_el.value +
        '&url=' +
        url_el.value;

        sendHTTPRequest('index.php', feedbackSent, null, post_params); //  POST
        return 1;
    }

    return 0;
}

function feedbackSent(xml_http, params)
{
    //alert(xml_http.responseText);

    var user_name_el = document.getElementById('fb_user_name');
    var email_el = document.getElementById('fb_email');
    var feedback_el = document.getElementById('fb_feedback');
    var feedback_type_id_el = document.getElementById('fb_feedback_type_id');
    var url_el = document.getElementById('fb_url');

    user_name_el.value = '';
    email_el.value = '';
    feedback_el.value = '';
    feedback_type_id_el.value = 1;

    showAlert(i18n['m1420']); //Thank you for your feedback! We really appreciate it.
}


/*
 function sendFavourite(favEl, videoId, userId)
 {
 favEl.old = favEl.onclick;
 favEl.onclick = '';
 sendHTTPRequest('index.php?service=videos&action=addfavorite&video_id=' + videoId + '&user_id=' + userId, setFavourite, favEl);
 }
 function setFavourite(xml_http, favEl)
 {
 var favorited = xml_http.responseXML.getElementsByTagName('favorited').item(0).firstChild.nodeValue;
 var isFavourite = xml_http.responseXML.getElementsByTagName('is-favourite').item(0).firstChild.nodeValue;
 document.getElementById('video_favorited').firstChild.nodeValue = favorited;
 if ( isFavourite == 0 )
 {
 alert(i18n['m0524']); //This video has been removed from your favorites.
 favEl.className = 'favorite';
 favEl.firstChild.nodeValue = i18n['m0116']; //Add to favorites
 }
 else
 {
 alert(i18n['m0525']); //This video has been added to your favorites.
 favEl.className = 'remfavorite';
 favEl.firstChild.nodeValue = i18n['m0117']; //Remove from favorites
 }
 favEl.onclick = favEl.old;
 }
 /* } favourite */
//  hovered buttons
function buttonPlain(button)
{
    button.className = button.oldClassName;
}

function buttonHovered(button, hoveredClass)
{
    if (hoveredClass == null)
    {
        hoveredClass = 'hovered';
    }

    button.oldClassName = button.className;
    button.className += (' ' + hoveredClass);
}

function loadingMessage(divEl)
{
    divEl.innerHTML = '';
    h3El = document.createElement('h3');
    h3El.appendChild(document.createTextNode(i18n['m0542'] ? i18n['m0542'] : 'Please wait while loading...'));
    nestedEl = document.createElement('div');
    nestedEl.className = 'no_data';
    nestedEl.appendChild(h3El);
    divEl.appendChild(nestedEl);
}

function sendIndexItemList(listStr, pageNo, perPage, sortId)
{
    if (!sortId)
    {
        sortId = 1;
    }
    listEl = document.getElementById(listStr);
    if (listEl.pageNo && listEl.pageNo != 0 && pageNo == 0)
    {
        if (listEl.perPage && listEl.perPage == perPage)
        {
            pageNo = listEl.pageNo;
            sortId = listEl.sortId;
        }
    }
    listEl.pageNo = pageNo;
    listEl.perPage = perPage;
    listEl.sortId = sortId;
    fixItem(listEl, 'hidden');

    els = listEl.childNodes;
    existEl = null;
    for (i = 0; i < els.length; i++)
    {
        if (els[i].id == pageNo + '_' + perPage + '_' + sortId)
        {
            els[i].className = '';
            existEl = els[i];
        }
        else
        {
            els[i].className = 'hidden';
        }
    }
    if (!existEl)
    {
        divEl = listEl.appendChild(document.createElement('div'));
        divEl.setAttribute('id', pageNo + '_' + perPage + '_' + sortId);
        loadingMessage(divEl);
        var params = new Array(divEl, 0);
        sendHTTPRequest('ajax/xml_indexlist/?&list_id=' + listStr + '&pn=' + pageNo + '&pp=' + perPage, setItemList, params);
    }
}

function sendPlaylistItemList(playlistId, pageNo, perPage, page_flag)
{
    if (page_flag == 2)
    {
        listEl = document.getElementById('movie_list');
    }
    else
    {
        listEl = document.getElementById('pl_video' + playlistId);
    }
    loadingMessage(listEl);
    var params = new Array(listEl);
    sendHTTPRequest('ajax/playlists/?&playlist_id=' + playlistId + '&pn=' + pageNo + '&pp=' + perPage + '&page_flag=' + page_flag, setItemList, params);
}

function sendPlaylistListItemList(pageNo, perPage, sort_by)
{
    listEl = document.getElementById('playlist_container');
    var params = new Array(listEl);
    sendHTTPRequest('ajax/xml_playlistlist/?&pn=' + pageNo + '&pp=' + perPage + '&sort_by=' + sort_by, setItemList, params);
}

function sendDashboardCreatorItemList(listStr, pageNo, perPage, sortId, creatorId, mode)
{
    listEl = document.getElementById(listStr);
    if (listEl.pageNo && listEl.pageNo != 0 && pageNo == 0)
    {
        if (listEl.perPage && listEl.perPage == perPage) 
        {
            pageNo = listEl.pageNo;
            sortId = listEl.sortId;
        }
    }
    listEl.pageNo = pageNo;
    listEl.perPage = perPage;
    listEl.sortId = sortId;
    
	fixItem(listEl, 'hidden');

	els = listEl.childNodes;
	existEl = null;
    for (i = 0; i < els.length; i++)
    {
        if (els[i].id == pageNo + '_' + perPage + '_' + sortId)
        {
            els[i].className = '';
            existEl = els[i];
        }
        else
        {
            els[i].className = 'hidden';
        }
    }
    if (!existEl)
    {
        divEl = listEl.appendChild(document.createElement('div'));
        divEl.setAttribute('id', mode + '_' + pageNo + '_' + perPage + '_' + sortId);
        loadingMessage(divEl);
        var params = new Array(divEl, 0);
        switch(mode) {
        	case 'p':
        		sendHTTPRequest('dashboard/published/?&creator_id=' + creatorId + '&sort=' + sortId + '&list_id=' + listStr + '&pn=' + pageNo + '&pp=' + perPage + '&mode=' + mode, setItemList, params);
        		break;
        	case 'h':
        		sendHTTPRequest('dashboard/history/?&creator_id=' + creatorId + '&sort=' + sortId + '&list_id=' + listStr + '&pn=' + pageNo + '&pp=' + perPage + '&mode=' + mode, setItemList, params);
        		break;
        	case 'a':
        		sendHTTPRequest('dashboard/submitted/?&creator_id=' + creatorId + '&sort=' + sortId + '&list_id=' + listStr + '&pn=' + pageNo + '&pp=' + perPage + '&mode=' + mode, setItemList, params);
        		break;
        	case 'uph':
            	sendHTTPRequest('ajax/xml_user_photoslist/?&creator_id=' + creatorId + '&sort=' + sortId + '&list_id=' + listStr + '&pn=' + pageNo + '&pp=' + perPage + '&mode=' + mode, setItemList, params);        		
        		break;
        	case 'ph':
            	sendHTTPRequest('ajax/xml_user_photoslist/?&creator_id=' + creatorId + '&sort=' + sortId + '&list_id=' + listStr + '&pn=' + pageNo + '&pp=' + perPage + '&mode=' + mode, setItemList, params);        		
        		break;
        
        }
    }
}

function validateDashboardVideoForm(formId) {

		var options = {
				success: function(response) {
                    var divEl = $("#paged_video_list").get(0);
                    var params = new Array(divEl, 0);
                    setItemList({responseText : response}, params);
                }
		};

		$("#members_change_video_info"+formId).validate(
				{
					submitHandler : function(form) {

						$(form).ajaxSubmit(options);
					},
					rules : {
						title : {
							required : true,
							maxlength : 50 
						},
						tag: {
			                tags:'',
			                required: true,
			                maxlength: 150
			            },
						credits : {
							required: false,
			                maxlength: 10000
						},
						checkboxes_validator: {
			                required: {
			                    depends: function() {                        
			                        return (!$('#members_change_video_info'+formId+' input[@type=checkbox]:checked').length > 0);
			                    }
			                }
			            },
						description : {
							required: true,
			                maxlength: 10000
						}

					},
					messages : {
						title : i18n['m0794'],
						tag : i18n['m0796'],
						credits :  i18n['m0763'],
						checkboxes_validator: i18n['m0797'],
						description : i18n['m0795']
					},
					errorElement : 'div',
					errorPlacement : function(error, element) {
						var parentDiv = element.parent();
						//parentDiv.after('<div class="error">'+error+'</div>');
						parentDiv.after(error);
						//error.appendTo(parentDiv);
			        }
				});


}

function sendSubscriptionItemList(subscriptionId, date, pageNo, perPage)
{
    listEl = document.getElementById('subvideo' + subscriptionId);
    loadingMessage(listEl);
    var params = new Array(listEl);
    sendHTTPRequest('ajax/subscriptions/?&creator_id=' + subscriptionId + '&date=' + date + '&pn=' + pageNo + '&pp=' + perPage, setItemList, params);
}

function checkUsernameStatus(username)
{
    listEl = $('#join_login_error');
	listEl.hasClass('hidden') ? '' : listEl.addClass('hidden');
    var d = new Date();
    if (username != '' && username.length > 2)
    {
        $.get('ajax/xml_join_checklogin/?login=' + username + '&t=' + d.getTime(),
        	function(data)
        	{
	   			if(data)
	   			{
	   				listEl.removeClass('hidden')
	   				listEl.html(data);
	   			}
 		});
    }
}

function checkBlocked(user_id)
{
    $.get('ajax/xml_check_blocked/?userid=' + user_id,
        function(data)
        {
            isBlocked = data.getElementsByTagName('is-blocked').item(0).firstChild.nodeValue;
            if (isBlocked == 1)
            {
                showAlert('You cannot send a message to this user.');
            }
            else
            {
                 toggleEll('send_mes');
            }
        
        });
}

function setItemList(xml_http, params)
{
    params[0].innerHTML = xml_http.responseText;
/*    try {
    	tinymce.dom.Event._pageInit();
    	tinyMCE.init({
			mode : "specific_textareas",
			theme : "simple",
			entity_encoding : "raw",
			editor_selector : "mce_editor",
			remove_trailing_nbsp : true,
			valid_elements: "span/b[class=bold],span/strong[class=bold],p,b,i,u,strike,ul,li,ol",
			invalid_elements: "script, object, applet, iframe"
	   });
    }
    catch (e){
    }*/
}


function createPlaylist(button_el)
{
    var pl_name_el = document.getElementById('playlist_new');
    if (pl_name_el.value.length == 0)
    {
        showAlert(i18n['m0717']); //Please indicate your playlist title.
        return false;
    }
    buttonPlain(button_el);
    button_el.disabled = true;
    //encodeURI for IE 6,7 (decode russian symbol, japanese etc)
    sendHTTPRequest('ajax/playlists_create/?&playlist=' + encodeURI(pl_name_el.value), addNewPlaylist, button_el);
}

function addNewPlaylist(xml_http, button_el)
{
    if (xml_http.responseXML.getElementsByTagName('error-message').length > 0)
    {
        showAlert(xml_http.responseXML.getElementsByTagName('error-message').item(0).firstChild.nodeValue);
        button_el.disabled = false;
        return false;
    }
    var pl_el = xml_http.responseXML.getElementsByTagName('playlist').item(0);
    var pl_id = pl_el.getElementsByTagName('id').item(0).firstChild.nodeValue;
    var pl_title = pl_el.getElementsByTagName('name').item(0).firstChild.nodeValue;
    var option_el = document.createElement('option');
    option_el.appendChild(document.createTextNode(pl_title));
    option_el.setAttribute('value', pl_id);
    var select_el = document.getElementById('playlist_name');
    select_el.appendChild(option_el);
    button_el.disabled = false;
    showAlert(i18n['m0718']); //New playlist has been created.
}

function addVideoToPlaylist(button_el, video_id)
{
    var select_el = document.getElementById('playlist_name');
    playlist_id = select_el.options[select_el.selectedIndex].value;

    buttonPlain(button_el);
    button_el.disabled = true;
    sendHTTPRequest('ajax/playlists_add_video/?&playlist_id=' + playlist_id.toString() + '&video_id=' + video_id.toString(), sendCommandToAddVideoToPlaylist, button_el);
}

function sendCommandToAddVideoToPlaylist(xml_http, button_el)
{
    var message = xml_http.responseXML.getElementsByTagName('message').item(0).firstChild.nodeValue;
    button_el.disabled = false;
    showAlert(message);
}

function renamePlaylist(button_el, id)
{
    var pl_name_el = document.getElementById('pl_name' + id);
    var pl_id_el = document.getElementById('playlist_id' + id);
    var pl_description_el = document.getElementById('pl_desc' + id);
    var form = document.getElementById('rename_form' + id);
    var inputs = form.getElementsByTagName('input');
    status = 0;
    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'radio')
        {
            if (inputs[i].checked)
            {
                statuspl = inputs[i].value;

            }
        }
    }
    if (pl_name_el.value.length == 0)
    {
        showAlert(i18n['m0717']); //Please indicate your playlist title.
        return false;
    }

    if (pl_description_el.value.length == 0)
    {
        showAlert(i18n['m1375']); //Please discribe your playlist.
        return false;
    }

    if (pl_description_el.value.length > 200)
    {
        showAlert(i18n['m1376']); //Description should be between 0 to 200 characters. Please try again.
        return false;
    }

    buttonPlain(button_el);
    button_el.disabled = true;
    toggleEll('rename_form' + id);
    toggleEll('pl' + id);

    sendHTTPRequest('ajax/playlists_edit_info/?&playlist_id=' + pl_id_el.value + '&playlist_name=' +
        encodeURI(pl_name_el.value) +
        '&desc=' +
        encodeURI(pl_description_el.value) +
        '&status=' +
        statuspl, sendPlaylistNewName, button_el);
}


function sendPlaylistNewName(xml_http, button_el, id)
{
    if (xml_http.responseXML.getElementsByTagName('error-message').length > 0)
    {
        showAlert(xml_http.responseXML.getElementsByTagName('error-message').item(0).firstChild.nodeValue);
        button_el.disabled = false;
        return false;
    }

    var pl_el = xml_http.responseXML.getElementsByTagName('playlist').item(0);
    var pl_id = pl_el.getElementsByTagName('id').item(0).firstChild.nodeValue;
    var pl_title = pl_el.getElementsByTagName('name').item(0).firstChild.nodeValue;
    var pl_status = pl_el.getElementsByTagName('is-private').item(0).firstChild.nodeValue;
    var pl_description = pl_el.getElementsByTagName('description').item(0).firstChild.nodeValue;
    if (pl_status == 0)
    {
        pl_status = 'public';
    }
    else
    {
        pl_status = 'private';
    }
    //var pl_description = pl_el.getElementsByTagName('description').item(0).firstChild.nodeValue;

    var name_el = document.getElementById('vs_name' + pl_id);
    name_el.innerHTML = pl_title;

    var status_el = document.getElementById('vs_status' + pl_id);
    status_el.innerHTML = pl_status;

    var desc_el = document.getElementById('vs_description' + pl_id);
    desc_el.innerHTML = pl_description;

    button_el.disabled = false;
    showAlert(i18n['m1377']); //Playlist info updated successfully.
}

function checkedCount(target_el)
{
    var inputs = target_el.getElementsByTagName('input');
    var checkboxes = 0;

    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'checkbox')
        {
            if (inputs[i].checked == "1")
            {
                checkboxes++;
            }
        }
    }

    if (checkboxes != 0)
    {
        return checkboxes;
    }
    else
    {
        return false;
    }
}

function checkSelected(target_el)
{
    if (!checkedCount(target_el))
    {
        showAlert(i18n['m1378']); //Please select at list one video.
        return false;
    }
    else
    {
        return true;
    }

}

function addVideoToQuickList(video_id, type, targetel)
{
    sendHTTPRequest('ajax/playlists_add_video/?&playlist_type_id=' + type.toString() +
        '&video_id=' +
        video_id.toString(), stub); // KLUDGE: may be javascript:void
    targetel.className = 'tick';
    targetel.setAttribute('title', i18n['m1389']); //Video added to Quicklist
}

//check to 3 categories
function checkChecked(formId, limit, th)
{
    var formEl = $(th).parents('form[name=' + formId + ']').get(0);
    if(!formEl)
    {
        formEl = document.getElementById(formId);
    }

    if (!formEl.tempElements)
    {
        formEl.tempElements = [];
    }


    if(arguments[3])
    {
        if(!formEl.tempElements[arguments[3]])
        {
            formEl.tempElements[arguments[3]] = [];
        }
        formEl.tempEls = formEl.tempElements[arguments[3]];
    }
    else
    {
        formEl.tempEls = formEl.tempElements;
    }

    
    if(th.checked == true)
    {
        if(formEl.tempEls.length >= limit)
        {
            var old = formEl.tempEls.shift();
            if(old)
            {
                old.checked = false;
            }
        }
        formEl.tempEls.push(th);
    }
    else
    {
        formEl.tempEls.pop();
    }
}

function formCheckboxInit(divId)
{
	var form = $("#"+divId+" form").get(0);
	var checkboxArray = $("#"+divId+" form input[@type=checkbox]:checked");
    if (!form.tempElements)
    {
        form.tempElements = [];
    }

	for (var i = 0; i<checkboxArray.length; i++) {
		form.tempElements.push(checkboxArray[i]);
	}
}

function formMultiCheckboxInit(formId, divId)
{
    var formEl = '',
    checkboxArray = [];

    formEl = $('form[name=' + formId + ']').get(0);
    if(!formEl)
    {
        formEl = document.getElementById(arguments[1]);
    }
    
    checkboxArray = $(formEl).find('#' + divId + ' input[@type=checkbox]:checked');

    if (!formEl.tempElements)
    {
        formEl.tempElements = [];
    }
    if(!formEl.tempElements[divId])
    {
        formEl.tempElements[divId] = [];
    }

    for (var i = 0; i<checkboxArray.length; i++) {
        formEl.tempElements[divId].push(checkboxArray[i]);
    }
}
/* inmail { */

function showMail(targetEl, mailId)
{
    var els = targetEl.parentNode.getElementsByTagName('tr');
    for (i = 1; i < els.length; i += 2)
    {
        trBodyEl = (els[i].nextSibling.nodeName.toLowerCase() == 'tr') ? els[i].nextSibling : els[i].nextSibling.nextSibling;
        if (els[i] == targetEl)
        {
            trBodyEl.className = (trBodyEl.className == 'hidden') ? '' : 'hidden';
        }
        else
        {
            els[i].className = '';
            trBodyEl.className = 'hidden';
        }
    }
    if (targetEl.getAttribute('read') != 1)
    {
        sendReadMail(targetEl, mailId)
    }
}

function sendReadMail(targetEl, mailId)
{
    //targetEl.old = targetEl.onclick;
    //targetEl.onclick = '';
    sendHTTPRequest('index.php?service=inmails&action=read_mail&mail_id=' + mailId, setReadMail, targetEl);
}

function setReadMail(xml_http, targetEl)
{
    var isRead = xml_http.responseXML.getElementsByTagName('is-read').item(0).firstChild.nodeValue;
    if (isRead == 1)
    {
        targetEl.style.fontWeight = 'normal';
        targetEl.setAttribute('read', 1);
    }
//targetEl.onclick = targetEl.old;
}

function toggleAllCheckbox(formId, targetEl)
{
    var formEl = document.getElementById(formId);
    var inputEls = formEl.getElementsByTagName('input');
    for (i = 0; i < inputEls.length; i++)
    {
        if (inputEls[i].type == 'checkbox')
        {
            if (targetEl != inputEls[i])
            {
                inputEls[i].checked = targetEl.checked;
            }
        }
    }
}

function cancelBubble(event)
{
    if (!event)
    {
        event = window.event;
    }
    event.cancelBubble = true;
}

/* } inmail */

function changeFormAction(id, action)
{
    document.getElementById(id).action = action;
//   alert(document.getElementById(id).action);
}

function getCheckedPlaylists(targetel)
{
    var inputs = document.getElementsByTagName('input');
    var checkboxes = new Array();
    var j = 0;

    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'checkbox')
        {
            if (inputs[i].checked == "1")
            {
                checkboxes[j] = inputs[i].value;
                j++;
            }
        }
    }
    if (j != 0)
    {
        targetel.playlist_ids.value = checkboxes;
        targetel.submit();
        return true;
    }
    else
    {
        showAlert(i18n['m1385']); //Please select at list one playlist.
        return false;
    }
}

function getCheckedSubscribers(targetel)
{
    var inputs = document.getElementsByTagName('input');
    var checkboxes = new Array();
    var j = 0;

    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'checkbox')
        {
            if (inputs[i].checked == "1")
            {
                checkboxes[j] = inputs[i].value;
                j++;
            }
        }
    }
    if (j != 0)
    {
        targetel.users_ids.value = checkboxes;
        if (confirm(i18n['m1386'])) //Are you sure you want to unsubscribe?
        {
            targetel.submit();
        }
        return true;
    }
    else
    {
        showAlert(i18n['m1387']); //Please select at list one subscriber.
        return false;
    }
}

function toggleAllCheckboxByName(name, targetEl)
{
    var inputEls = document.getElementsByTagName('input');
    for (i = 0; i < inputEls.length; i++)
    {
        if (inputEls[i].type == 'checkbox')
        {
            if (inputEls[i].name == name)
            {
                inputEls[i].checked = targetEl.checked;
            }
        }
    }
    return true;
}

function getSelectedVideos(playlist_id)
{
    var playlist = document.getElementById('pl_video' + playlist_id);
    var inputs = playlist.getElementsByTagName('input');
    var checkboxes = new Array();
    var j = 0;

    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'checkbox')
        {
            if (inputs[i].checked == "1")
            {
                checkboxes[j] = inputs[i].value;
                j++;
            }
        }
    }
    if (j != 0)
    {
        return checkboxes;
    }
    else
    {
        return false;
    }
}

function copyPlaylistVideos(playlist_id, target_button)
{
    video_ids = getSelectedVideos(playlist_id);
    if (!video_ids)
    {
        showAlert(i18n['m1378']); //Please select at list one video.
        return false;
    }
    buttonPlain(target_button);
    target_button.disabled = true;

    playlist_target_id = document.getElementById('playlist_target_id' + playlist_id).value;
    var params = new Array(playlist_target_id, playlist_id, target_button);
    sendHTTPRequest('ajax/playlists_copy_videos/?&playlist_source_id=' + playlist_id + '&playlist_target_id=' + playlist_target_id + '&video_ids=' + video_ids, playlistsApplyChanges, params);
}

function playlistsApplyChanges(xml_http, params)
{
    var playlist_type = xml_http.responseXML.getElementsByTagName('playlist-type').item(0).firstChild.nodeValue;
    var message = xml_http.responseXML.getElementsByTagName('message').item(0).firstChild.nodeValue;
    var pl_message = document.getElementById('pl_message' + params[1]);
    params[2].disabled = false;
    pl_message.innerHTML = message;

    if (playlist_type == '1')
    {
        sendPlaylistItemList(params[0], 0, 10);
    }
}

function deletePlaylistVideos(playlist_id, target_button)
{
    video_ids = getSelectedVideos(playlist_id);
    if (!video_ids)
    {
        showAlert(i18n['m1378']); //Please select at list one video.
        return false;
    }
    buttonPlain(target_button);
    target_button.disabled = true;

    var params = new Array(playlist_id, target_button);
    sendHTTPRequest('ajax/playlists_delete_videos/?&playlist_source_id=' + playlist_id + '&video_ids=' + video_ids, playlistsShowChanges, params);
}

function playlistsShowChanges(xml_http, params)
{
    var message = xml_http.responseXML.getElementsByTagName('message').item(0).firstChild.nodeValue;
    //var pl_message = document.getElementById('pl_message'+params[0]);
    //var cur_page = document.getElementById('cur_page'+params[0]).firstChild.nodeValue;
    //alert(cur_page);
    if (params[1])
    {
        params[1].disabled = false;
    }
    //pl_message.innerHTML = message;
    sendPlaylistItemList(params[0], 0, 10);

}

function getVideosPriorities(playlist_id)
{
    var playlist = document.getElementById('pl_video' + playlist_id);
    var inputs = playlist.getElementsByTagName('input');
    var priorities = new Array();
    var video_ids = new Array();
    var j = 0;
    var k = 0;

    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].getAttribute('name') == 'priority')
        {
            priorities[j] = inputs[i].value;
            j++;
        }
        if (inputs[i].getAttribute('name') == 'sel')
        {
            video_ids[k] = inputs[i].value;
            k++;
        }
    }
    var video_priorities = new Array(priorities, video_ids);
    //alert(video_priorities[0]);
    //alert(video_priorities[1]);
    return video_priorities;
}

function validatePriority(target_el, video_id, playlist_id)
{
    digits = "0123456789";
    old_value = document.getElementById('priorityoldvalue' + video_id + '[' + playlist_id + ']').firstChild.nodeValue;
    if (target_el.value.length > 3)
    {
        target_el.value = target_el.value.substr(0, 3);
        return false;
    }

    if (target_el.value <= 0)
    {
        target_el.value = old_value;
    }
    for (i = 0; i < target_el.value.length; i++)
    {
        if (digits.indexOf(target_el.value.charAt(i)) == -1)
        {

            if (target_el.value.length - 1 != 0)
            {
                target_el.value = target_el.value.substr(0, target_el.value.length - 1);
            }
            else
            {
                target_el.value = old_value;
            }

            return false;
        }
    }

    return true;
}

function rearrangePlaylistVideos(playlist_id, video_id, new_priority)
{
    old_priority = document.getElementById('priorityoldvalue' + video_id + '[' + playlist_id + ']').firstChild.nodeValue;
    var params = new Array(playlist_id, null);
    sendHTTPRequest('ajax/playlists_rearrange/?&playlist_source_id=' + playlist_id + '&video_id=' + video_id + '&new_priority=' + new_priority + '&old_priority=' + old_priority, playlistsShowChanges, params);
}

function setActionType(params)
{
    form_id = params[0];
    form_type = params[1];
    var quicklistform = document.getElementById(form_id);
    quicklistform.action_type.value = form_type;
    quicklistform.submit();
}

function clearPlaylist(playlist_id, target_button)
{
    buttonPlain(target_button);
    target_button.disabled = true;

    var params = new Array(playlist_id, target_button);
    sendHTTPRequest('ajax/playlists_clear/?&playlist_source_id=' + playlist_id, playlistsShowChanges, params);
}

function showMenu(targetEl)
{
    targetEl.parentNode.timer = setTimeout(function(arg)
    {
        return function()
        {
            showMenuST(arg);
        }
    }(targetEl), 300);
}

function showMenuST(targetEl)
{
    var els = targetEl.parentNode.getElementsByTagName('div');
    for (i = 0; i < els.length; i += 2)
    {
        subMemuEl = (els[i].nextSibling.nodeName.toLowerCase() == 'div') ? els[i].nextSibling : els[i].nextSibling.nextSibling;
        if (els[i] == targetEl)
        {
            subMemuEl.className = (subMemuEl.className == 'hidden') ? 'corp_m_b' : 'hidden';
            els[i].className = (subMemuEl.className == 'hidden') ? 'left_block_header corp_m' : 'left_block_header';
        }
        else
        {
            els[i].className = 'left_block_header corp_m';
            subMemuEl.className = 'hidden';
        }
    }
}

/**VIDEOS view mode**/
function changeVideosViewMode(mode, viewId)
{
    var list_view_button_el = document.getElementById(viewId + '_list_button');
    var table_view_button_el = document.getElementById(viewId + '_table_button');
    var visual_view_button_el = document.getElementById(viewId + '_visual_button');
    var list_view_container_el = document.getElementById(viewId + '_list_container');
    var table_view_container_el = document.getElementById(viewId + '_table_container');
    var visual_view_container_el = document.getElementById(viewId + '_visual_container');


    if (list_view_container_el == null)
    {
        return;
    }

    switch (mode)
    {
        //  table view
        case 1: //videos
        //visual_view_button_el.className = 'videos_view_button v_visual';
        //visual_view_container_el = 'hidden';
        case 2: //video and channel detail
            list_view_button_el.className = 'videos_view_button v_list';
            table_view_button_el.className = 'videos_view_button v_table fixed';
            list_view_container_el.className = 'hidden';
            table_view_container_el.className = '';
            break;
        //  list view
        case 0: //videos
        //visual_view_button_el.className = 'videos_view_button v_visual';
        //visual_view_container_el = 'hidden';
        case 3: //video and channel detail
            list_view_button_el.className = 'videos_view_button v_list fixed';
            table_view_button_el.className = 'videos_view_button v_table';
            list_view_container_el.className = '';
            table_view_container_el.className = 'hidden';
            break;
        // visual mode
        case 4: //video and channel detail
            //list_view_button_el.className = 'videos_view_button v_list';
            //table_view_button_el.className = 'videos_view_button v_table';
            //visual_view_button_el.className = 'videos_view_button v_visual fixed';
            //list_view_container_el.className = 'hidden';
            //table_view_container_el.className = 'hidden';
            //visual_view_container_el = '';
            break;
    }
    var today = new Date();
    var expire = new Date();
    expire.setTime((today.getTime() + 3600000 * 24 * 30)); //  30 days
    if (mode == 0 || mode == 1 || mode == 4)
    {
        setCookie('videos_view_mode', mode, expire.toGMTString(), '/');
    }
    else
    {
        setCookie('detail_view_mode', mode, expire.toGMTString(), '/');
    }
}

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
}

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 "";
}

function in_array(needle, haystack, argStrict) {

    var key = '', strict = !!argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function array_unique(array)
{
    var key = '', tmp_arr1 = {}, tmp_arr2 = [];
    var val = '';
    tmp_arr1 = array;
    var __array_search = function(needle, haystack, strict)
    {
        var fkey = '';
        var strict = !!strict;
        for (fkey in haystack)
        {
            if ((strict && haystack[fkey] === needle) || (!strict && haystack[fkey] == needle))
            {
                return fkey;
            }
        }
        return false;
    }
    for (key in tmp_arr1)
    {
        val = tmp_arr1[key];
        if (false === __array_search(val, tmp_arr2))
        {
            tmp_arr2[tmp_arr2.length] = val;
        }

        delete tmp_arr1[key];
    }
    return tmp_arr2;
}



function showDescription(el)
{
    el.parentNode.className = 'hidden';
    el.parentNode.nextSibling.nodeType == 1 ? el.parentNode.nextSibling.className = '' : el.parentNode.nextSibling.nextSibling.className = '';
}

function hideDescription(el)
{
    el.parentNode.className = 'hidden';
    el.parentNode.previousSibling.nodeType == 1 ? el.parentNode.previousSibling.className = '' : el.parentNode.previousSibling.previousSibling.className = '';
}

/**end VIDES view mode**/

function showAlert(msg, callbackFunction, params)
{
    bodyEl = document.getElementsByTagName('body')[0];

    inputEl = document.createElement('input');
    inputEl.type = 'button';
    inputEl.value = i18n['m0814'] ? i18n['m0814'] : 'Ok';
    inputEl.className = 'button inner_mes_but';
    inputEl.onmouseover = function()
    {
        buttonHovered(this);
    };
    inputEl.onmouseout = function()
    {
        buttonPlain(this);
    };
    inputEl.onclick = function()
    {
        bodyEl.removeChild(document.getElementById('show_alert'));
        if (callbackFunction)
        {
            callbackFunction(params ? params : new Array());
        }
    };

    imgTextEl = document.createElement('img');
    imgTextEl.src = 'design/images/int-warning.gif';

    pTextEl = document.createElement('p');
    pTextEl.appendChild(document.createTextNode(msg));

    divTextEl = document.createElement('div');
    divTextEl.className = 'alert_text';

    divTextEl.appendChild(imgTextEl);
    divTextEl.appendChild(pTextEl);
    divTextEl.appendChild(inputEl);

    inputEl.style.cssText = "display:block;margin-top:25px;";

    aCloseEl = document.createElement('a');
    aCloseEl.className = 'close';
    aCloseEl.href = 'javascript: void(0);';
    aCloseEl.onclick = function()
    {
        bodyEl.removeChild(document.getElementById('show_alert'));
        if (callbackFunction)
        {
            callbackFunction(params ? params : new Array());
        }
    };

    divCloseEl = document.createElement('div');
    divCloseEl.className = 'close_div';
    divCloseEl.appendChild(aCloseEl);

    divInnerEl = document.createElement('div');
    divInnerEl.className = 'inner_mes';
    //divInnerEl.setAttribute('style', 'text-align: center; font-size: 20px; margin-top: 30px;');
    divInnerEl.appendChild(divCloseEl);
    divInnerEl.appendChild(divTextEl);

    divOuterEl = document.createElement('div');
    divOuterEl.className = 'outer_mes';

    divAlertEl = document.createElement('div');
    divAlertEl.setAttribute('id', 'show_alert');
    divAlertEl.appendChild(divOuterEl);
    divAlertEl.appendChild(divInnerEl);

    bodyEl.appendChild(divAlertEl);
    inputEl.focus();
}

function showLoginForm(url, msg)
{
    bodyEl = document.getElementsByTagName('body')[0];

    divClearerEl = document.createElement('div');
    divClearerEl.className = 'clearer';

    inputRefererEl = document.createElement('input');
    inputRefererEl.type = 'hidden';
    inputRefererEl.name = 'referer';
    inputRefererEl.value = url;

    inputPostedBackEl = document.createElement('input');
    inputPostedBackEl.type = 'hidden';
    inputPostedBackEl.name = 'posted_back';
    inputPostedBackEl.value = 'members_login';

    inputLoginEl = document.createElement('input');
    inputLoginEl.type = 'text';
    inputLoginEl.name = 'login';
    inputLoginEl.maxLength = '25';
    inputLoginEl.setAttribute('maxlength', '25');

    inputPassEl = document.createElement('input');
    inputPassEl.type = 'password';
    inputPassEl.name = 'password';
    inputPassEl.maxLength = '20';
    inputPassEl.setAttribute('maxlength', '20');

    inputSubmitEl = document.createElement('input');
    inputSubmitEl.type = 'submit';
    inputSubmitEl.value = i18n['m0008'] ? i18n['m0008'] : 'Log In';
    inputSubmitEl.className = 'button inner_mes_but_log';
    inputSubmitEl.onmouseover = function()
    {
        buttonHovered(this);
    };
    inputSubmitEl.onmouseout = function()
    {
        buttonPlain(this);
    };

    aJoinEl = document.createElement('a');
    aJoinEl.href = 'join/';
    aJoinEl.appendChild(document.createTextNode(i18n['m0064'] ? i18n['m0064'] : 'Join Now!'));

    pJoinEl = document.createElement('p');
    pJoinEl.className = 'join';
    pJoinEl.appendChild(document.createTextNode(i18n['m0724'] ? i18n['m0724'] : 'Do not have an account?'));
    pJoinEl.appendChild(aJoinEl);

    formLoginEl = document.createElement('form');
    formLoginEl.action = 'login/';
    formLoginEl.method = 'post';
    formLoginEl.setAttribute('id', 'members_login');
    //formLoginEl.onsubmit = function () { return false; };
    formLoginEl.appendChild(inputPostedBackEl);
    formLoginEl.appendChild(inputRefererEl);
    formLoginEl.appendChild(inputLoginEl);
    formLoginEl.appendChild(inputPassEl);
    formLoginEl.appendChild(inputSubmitEl);

    imgTextEl = document.createElement('img');
    imgTextEl.src = 'design/images/int-warning.gif';

    pTextEl = document.createElement('p');
    pTextEl.appendChild(document.createTextNode(msg));

    divTextEl = document.createElement('div');
    divTextEl.className = 'alert_text';
    divTextEl.appendChild(imgTextEl);
    divTextEl.appendChild(pTextEl);
    divTextEl.appendChild(divClearerEl);
    divTextEl.appendChild(formLoginEl);
    divTextEl.appendChild(pJoinEl);
    divTextEl.appendChild(divClearerEl);

    aCloseEl = document.createElement('a');
    aCloseEl.className = 'close';
    aCloseEl.href = 'javascript: void(0);';
    aCloseEl.onclick = function()
    {
        bodyEl.removeChild(document.getElementById('show_alert'));
    };

    divCloseEl = document.createElement('div');
    divCloseEl.className = 'close_div';
    divCloseEl.appendChild(aCloseEl);

    divInnerEl = document.createElement('div');
    divInnerEl.className = 'inner_mes';
    divInnerEl.appendChild(divCloseEl);
    divInnerEl.appendChild(divTextEl);

    divOuterEl = document.createElement('div');
    divOuterEl.className = 'outer_mes';

    divAlertEl = document.createElement('div');
    divAlertEl.setAttribute('id', 'show_alert');
    divAlertEl.appendChild(divOuterEl);
    divAlertEl.appendChild(divInnerEl);

    bodyEl.appendChild(divAlertEl);
    inputSubmitEl.focus();
}

function stopUpload()
{
    try
    {
        document.execCommand('Stop');
    }
    catch (e)
    {
        window.stop();
    }
    clearInterval(window.imageTimer);
}

function applyFestivalFilter(element, link, id)
{
    sel_option_id = element.options[element.selectedIndex].value;
    document.location = link + '&' + id + '=' + sel_option_id;
}

/** Search Form **/
function searchToggleList(targetId)
{
    targetId = 'search_path_items';
    var listEl = document.getElementById(targetId);
    listEl.className = (listEl.className == '') ? 'hidden' : '';
}

function searchSelectItem(targetEl, servicePath)
{
    document.getElementById('index_search').action = servicePath;
    /*var object_type;
	switch (servicePath)
	{
		case 'videos/': //videos
		    object_type = 1;
		    break;
		case 'channels/': //channels
		    object_type = 2;
		    break;
		case 'users/': //people
		    object_type = 3;
		    break;
		case 'reviews/': //reviews
			object_type = 4;
		    break;
		case 'blogs/': //blogs
			object_type = 5;
		    break;
		case 'filmfestivals/': //filmfestivals
			object_type = 6;
		    break;
	}
	alert(object_type);*/
    document.getElementById('search_path').firstChild.nextSibling.nodeValue = targetEl.getElementsByTagName('a').item(0).firstChild.nodeValue;
    fixItem(targetEl);
    searchToggleList('search_path_items');
}

function search(formId)
{
    checkSearchForm();
    document.getElementById('index_search').submit();
//if (checkSearchForm()) document.getElementById('index_search').submit();

}

function showSearchHintST(target_ell_id,result_ell_id,event)
{
    if (event.keyCode == 38 || event.keyCode == 40)
    {
        analyzeHintStatus(event.keyCode,result_ell_id,target_ell_id);
    }
    else
    {
        target_ell = document.getElementById(target_ell_id);
        if(target_ell.value.length >= 2)
        {
            target_ell.parentNode.timer = setTimeout(function(arg,arg2){
                return function(){
                    showSearchHint(arg,arg2);
                }
                }(target_ell_id,result_ell_id), 200);
        }
        else
        {
            return false;
        }
    }
}

function showSearchHint(target_ell_id,result_ell_id)
{
    target_ell = document.getElementById(target_ell_id);
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    tag = encodeURIComponent(target_ell.value);
    search_path = encodeURIComponent(document.getElementById('index_search').action);
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            if (req.status == 200)
            {
                result_ell = document.getElementById(result_ell_id);
                result_ell.className = '';
                result_ell.innerHTML = '';
                result_ell.innerHTML = (req.responseText);
            }
        }
    }
    req.open('post', 'ajax/show_hint/', true);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send("tag=" + tag + "&search_path=" + search_path);

}

function analyzeHintStatus(key_code,result_ell_id,target_ell_id)
{
    result_ell = document.getElementById(result_ell_id);
    titles = result_ell.getElementsByTagName('li');
    position = 'ups';

    for(i = 0; i<titles.length;i++)
    {
        if(titles[i].className.indexOf('current') != -1)
        {
            position = i;
        }

    }

    if(key_code == 38)//up
    {
        if(position == 'ups')
        {
            current_hint = titles.length-1;
        //titles[titles.length-1].className = 'current';
        }
        if(position == 0)
        {
            titles[0].className = '';
            current_hint = titles.length-1;
        //titles[titles.length-1].className = 'current';
        }
        if(position > 0)
        {
            titles[position].className = '';
            current_hint = position-1;
        //titles[position-1].className = 'current';
        }
    }
    if(key_code == 40)//down
    {
        if(position == 'ups')
        {
            current_hint = 0;
        //titles[0].className = 'current';
        }
        if(position == titles.length-1)
        {
            titles[titles.length-1].className = '';
            current_hint = 0;
        //titles[0].className = 'current';
        }
        if(position < titles.length-1)
        {
            titles[position].className = '';
            current_hint = position+1;
        //titles[position+1].className = 'current';
        }
    }
    titles[current_hint].className = 'current';
    target_ell = document.getElementById(target_ell_id);
    //alert(titles[current_hint]);
    target_ell.value = titles[current_hint].getElementsByTagName('a').item(0).firstChild.nodeValue;
    return true;
}

function visualizeCurrentHint(container_ell_id,target_ell)
{
    container_ell = document.getElementById(container_ell_id);
    hints = container_ell.getElementsByTagName('li');
    for(i = 0; i<hints.length;i++)
    {
        hints[i].className = '';
    }
    target_ell.className = 'current';
    return true;

}

function checkSearchForm(tag_el_id)
{
    if (tag_el_id)
    {
        var tagEl = document.getElementById(tag_el_id);
    }
    else
    {
        var tagEl = document.getElementById('search_tag');
    }
    if (tagEl.value.replace(/\s/g, '').length == 0)
    {

        //showAlert(i18n['m1419'] ? i18n['m1419'] : 'You should specify search criteria.');
        tagEl.value = '';
    //tagEl.focus();
    //return false;
    }
    return true;
}

/** end Search Form**/

function sendSurveyData()
{
    if (checkSurveyForm())
    {
        var form = document.getElementById('survey_form');
        var postParams = '';
        for (var i = 1; i <= 6; i++)
        {
            var pollEls = form.elements['polls[' + i + ']'];
            for (var j = 0; j < pollEls.length; j++)
            {
                if (pollEls[j].checked)
                {
                    postParams += 'polls[' + i + ']=' + pollEls[j].value + '&';
                    postParams += 'comments[' + i + ']=' + form.elements['comments[' + i + ']'].value + '&';
                    break;
                }
            }
        }

        sendHTTPRequest('/polls/vote/', surveyDataSent, null, postParams); //  POST
    //alert(postParams);
    }
    else
    {
    //showAlert('false');
    }


    toggleEll('survey_container');
    resetSurveyForm();
}

function surveyDataSent(xml_http, params)
{
    showAlert(xml_http.responseXML.getElementsByTagName('message').item(0).firstChild.nodeValue);
}

function checkSurveyForm()
{
    var form = document.getElementById('survey_form');
    var k = 0;
    for (var i = 1; i <= 6; i++)
    {
        var pollEls = form.elements['polls[' + i + ']'];
        for (var j = 0; j < pollEls.length; j++)
        {
            if (pollEls[j].checked)
            {
                k++;
                break;
            }
        }
    }

    return k > 0; //k == 6
}

function resetSurveyForm()
{
    document.getElementById('survey_form').reset();
}

/** Automatic hiding **/
function startHide(elId, interval)
{
    if (!interval)
    {
        interval = 500;
    }
    el = document.getElementById(elId);
    var f = function()
    {
        hideEl(elId);
    }
    el.timer = setTimeout(f, interval);
}

function cancelHide(elId)
{
    el = document.getElementById(elId);
    clearTimeout(el.timer);
}

function hideEl(ellId)
{
    var ell = document.getElementById(ellId);
    //alert(ell.className.substr(0, ell.className.indexOf('hidden')));
    var hidden_pos = ell.className.indexOf('hidden');
    if (hidden_pos > -1)
    {
        ell.className = ell.className.substr(0, hidden_pos) + ' hidden';
    }
    else
    {
        ell.className += ' hidden';
        }
        }

        function showEl(elId)
{
    var ell = document.getElementById(elId);
    //alert(ell.className.substr(0, ell.className.indexOf('hidden')));
    var hidden_pos = ell.className.indexOf('hidden');
    if (hidden_pos > -1)
    {
        ell.className = ell.className.substr(0, hidden_pos);
    }
}

function checkAge(type)
{
    var max_ell = document.getElementById('ax');
    var min_ell = document.getElementById('am');
    min = parseInt(min_ell.value);
    max = parseInt(max_ell.value);
    if (max < min)
    {
        if(type == 1)
        {
            max_ell.value = min_ell.value;
        }
        else
        {
            min_ell.value = max_ell.value;
        }
    }
    return true;
}

function clearForm(formEl)
{
    var inputEls = formEl.getElementsByTagName('input');
    for (i = 0; i < inputEls.length; i++)
    {
        if (inputEls[i].type == 'checkbox' || inputEls[i].type == 'radio')
        {
            inputEls[i].checked = false;
        }
        if (inputEls[i].type == 'text')
        {
            inputEls[i].value = '';
        }
    }
    var textareaEls = formEl.getElementsByTagName('textarea');
    for (i = 0; i < textareaEls.length; i++)
    {
        textareaEls[i].value = '';
    }
}

function printData(data)
{
    pw = window.open('', '_blank', 'width=760,height=500,menu bar=yes');
    pw.document.open('text/plain');
    pw.document.write(data);
    pw.document.close();
    if (window.print)
    {
        pw.print();
    }
    else
    {
        pw.alert(i18n['m1875'] ? i18n['m1875'] : 'To print this page, please use your browser menu or press Ctrl + P.');
    }
    pw.close();
}

function analyzeCountry(country_id, state_element_id)
{
    var state_ell = document.getElementById(state_element_id);
    if (country_id == 228)
    {
        state_ell.className = '';
    }
    else
    {
        state_ell.className = 'hidden';
    }
    return true;
}

function initMainMenu()
{
    menuEl = document.getElementById('main_menu');
    menuEl.loaded = true;
}

function analyzeDropDownStatus(target_el_id, dropdown_type)
{
    target_el = document.getElementById(target_el_id);
    if (target_el.className.indexOf('hidden') != -1)
    {
        if (dropdown_type == 1)
        {
            searchToggleList(target_el_id);
        }
        else
        {
            //menuEl = document.getElementById('main_menu');
            //if (menuEl.loaded == true)
            //{
            toggleEll(target_el_id);
        //initFade(target_el_id, 0, 20);
        //setOpacity(document.getElementById(target_el_id), 0);
        //}
        }
    }
    else
    {
        cancelHide(target_el_id);
    }

}

function setCurrentItem(target_el_id)
{
    target_el = document.getElementById(target_el_id);
    target_el.className = 'current';

}

function unsetCurrentItem(target_el_id, current_item)
{
    if (current_item != 1)
    {
        target_el = document.getElementById(target_el_id);
        target_el.className = '';
    }
}

function initFade(targetElId, opStart, opEnd)
{
    targetEl = document.getElementById(targetElId);
    var timer = 0;

    setOpacity(targetEl, 0);
    if (opStart > opEnd)
    {
        for (i = opStart; i >= opEnd; i--)
        {
            speed = 10;
            setTimeout(function(arg, arg2) { 
                return function() {
                    setOpacity(arg, arg2);
                }
            }(targetEl, i/2), timer*speed);
            timer++;
        }
    }
    else if (opStart < opEnd)
    {
        for (i = opStart; i <= opEnd; i++)
        {
            speed = Math.sqrt(2*10*i);
            setTimeout(function(arg, arg2) { 
                return function() {
                    setOpacity(arg, arg2);
                }
            }(targetEl, i/2), timer*speed);
            timer++;
        }
    }
    return false;
}

function setOpacity(targetEl, value)
{
    targetEl.style.opacity = value/10;
    targetEl.style.MozOpacity = (value/10);
    targetEl.style.KhtmlOpacity = (value/10);
    targetEl.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function changeColor(target_el,container_el_id)
{
    container_el = document.getElementById(container_el_id);
    target_el.className = 'sel_check_color master_list_'+target_el.value;
    container_el.className = 'master_list_'+target_el.value;
}

function addMasterListChanges(container_el_id,item_id)
{
    container_el = document.getElementById(container_el_id);
    if (container_el.value.indexOf(item_id) == -1)
    {
        if(container_el.value.length != 0)
        {
            container_el.value = container_el.value+','+item_id;
        //alert(container_el.value);
        }
        else
        {

            container_el.value = item_id;
        //alert(container_el.value);
        }

        return true;
    }
    else
    {
        return false;
    }
}

function saveMasterListChanges(changes_container_id,button_el)
{
    var changes_id_el = document.getElementById(changes_container_id);
    var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    changes_str = changes_id_el.value;
    reject_reasons = '';
    if (changes_str.length == 0)
    {
        showAlert('Please change something!');
        return false;
    }
    changes_arr = changes_str.split(',');
    var action_string = '';
    buttonPlain(button_el);
    button_el.disabled = true;
    for (i = 0; i < changes_arr.length; i++)
    {
        //get master item list container
        master_list_item_container = document.getElementById('master_item_container'+changes_arr[i]);
        //get item color
        item_color = document.getElementById('master_list_item_color['+changes_arr[i]+']').value;
        //get item picked status
        is_picked = document.getElementById('is_picked['+changes_arr[i]+']').checked;
        is_picked = is_picked ? 1 : 0;
        //get item approval status
        approvalstatus = document.getElementById('approvalstatus['+changes_arr[i]+']').value;
        //get item comment
        comment = encodeURIComponent(document.getElementById('comment['+changes_arr[i]+']').value);
        //get reject reasons
        if(approvalstatus == 2)
        {
            ml_inputs = master_list_item_container.getElementsByTagName('input');
            for (y = 0; y < ml_inputs.length; y++)
            {
                if (ml_inputs[y].type == 'checkbox' && ((ml_inputs[y].name.indexOf('reject['+changes_arr[i]+']')) >= 0) && ml_inputs[y].checked == "1")
                {
                    if(reject_reasons.length == 0)
                    {
                        reject_reasons = ml_inputs[y].value;
                    }
                    else
                    {
                        reject_reasons = reject_reasons+','+ml_inputs[y].value;
                    }
                }
            }
        }
        //form post parametrs string
        action_string = action_string+ 'master_list_item_color['+changes_arr[i]+']='+item_color+
        '&is_picked['+changes_arr[i]+']='+is_picked+'&approvalstatus['+changes_arr[i]+']='+approvalstatus+
        '&comment['+changes_arr[i]+']='+comment+'&reject_reasons['+changes_arr[i]+']='+reject_reasons+'&';
        reject_reasons = '';

    }
    req.onreadystatechange = function()
    {
        if (req.readyState == 4)
        {
            if (req.status == 200)
            {
                button_el.disabled = false;
                showAlert('Changes saved!');
                changes_id_el.value = '';
            }
        }
    }
    req.open('post', 'ajax/manage_master_list/', true);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    req.send(action_string);
}

function getcheckedCountByName(target_el_id,name)
{
    target_el = document.getElementById(target_el_id);
    var inputs = target_el.getElementsByTagName('input');
    var checkboxes = 0;

    for (i = 0; i < inputs.length; i++)
    {
        if (inputs[i].type == 'checkbox' && ((inputs[i].name.indexOf(name)) >= 0))
        {
            if (inputs[i].checked == "1")
            {
                checkboxes++;
            }
        }
    }

    if (checkboxes != 0)
    {
        return checkboxes;
    }
    else
    {
        return false;
    }
}

function deleteVideoFromMasterList(target_el_id,name)
{
    if(getcheckedCountByName(target_el_id,name))
    {
        target_el = document.getElementById(target_el_id);
        target_el.master_list_action_type.value = '2';
        target_el.submit();
        return true;
    }
    else
    {
        showAlert('Please select at list one video');
        return false;
    }
}

function initMainMenuWithEvents()
{
    var arr = [];
    arr = [];
    arr['id'] = "mm1";
    arr['filterName'] = "dashboard_categories_filter";
    arr['currentMenuItemName'] = "dashboard_main_menu";

    var el = document.getElementById(arr["id"]);
    el.onmouseout = function()
    {
        startHide('dashboard_categories_filter', 50);
        setCurrentItem('dashboard_main_menu');
        unsetCurrentItem('dashboard_main_menu', 1);
    //alert("'" + arr['id'] + "'");
    }
    //alert(arr['id'].toString());
    for (var i = 0; i < arr.length; i++)
    {
        var el = document.getElementById(arr["id"]);
        alert(el.onmouseout);
        el.onmouseout = function()
        {
            alert("'" + arr['id'] + "'");
        }
    //el.onmouseover = "alert('" + arr[i]["currentMenuItemName"] + "')";
    }
}

function setRoll(photo_id,target_el_id)
{
    target_el = document.getElementById(target_el_id+'['+photo_id+']');
    target_el.checked = true;
}

function getUserListByLogin(target_ell,result_ell_id)
{
    if(target_ell.value.length >= 3)
    {
        var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        tag = encodeURIComponent(target_ell.value);

        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                if (req.status == 200)
                {
                    result_ell = document.getElementById(result_ell_id);
                    result_ell.innerHTML = '';
                    result_ell.innerHTML = (req.responseText);
                /*
                    user = req.responseXML.getElementsByTagName('user').item(0);
	                user_id = user.getElementsByTagName('id').item(0).firstChild.nodeValue;
	                user_name = user.getElementsByTagName('login').item(0).firstChild.nodeValue;
                    result_ell = document.getElementById(result_ell_id);
                    option_el = document.createElement('option');
	                option_el.appendChild(document.createTextNode(user_name));
	                option_el.setAttribute('value', user_id);
	               	result_ell.appendChild(option_el);*/
                }
            }
        }
        req.open('post', '3ce7ce8e886d09d8fdde1a75b615b115/', true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send("tag=" + tag);
    }
    else
    {
        return false;
    }
}

function getFestivalListByTitle(target_ell,result_ell_id)
{
    if(target_ell.value.length >= 3)
    {
        var req = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        tag = encodeURIComponent(target_ell.value);

        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                if (req.status == 200)
                {
                    result_ell = document.getElementById(result_ell_id);
                    result_ell.innerHTML = '';
                    result_ell.innerHTML = (req.responseText);
                }
            }
        }
        req.open('post', 'f0c46fdcbca9c847849391330877dfdd/', true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send("tag=" + tag);
    }
    else
    {
        return false;
    }
}

function checkApprovalStatus(video_id)
{
    target_el_select = document.getElementById('approvalstatus['+video_id+']');
    if(target_el_select.value == 2)
    {
        if(getcheckedCountByName('master_item_container'+video_id,'reject['+video_id+']'))
        {
            addMasterListChanges('master_list_changes',video_id);
            return true;
        }
        else
        {
            target_el_select.value = 5;
            showAlert('Please specify reject reasons first!!!');
            return false;
        }
    }
    else
    {
        addMasterListChanges('master_list_changes',video_id);
        return true;
    }


}

function setUserOnlineStatus()
{
    //setInterval(function() { return function() { sendHTTPRequest('ajax/set_user_online_status/', userOnlineStatusSet); } }(), 1000*ini['ONLINE_TIME']);
    setInterval(function() { 
        return function() {
            sendHTTPRequest('ajax/set_user_online_status/', userOnlineStatusSet);
        }
    }(), 1000*ini['ONLINE_TIMEOUT']);
}

function userOnlineStatusSet(xml_http)
{
	elem = xml_http.responseXML;
	if (elem)
	{
	    var inboxCount = elem.getElementsByTagName('new-inbox-count').item(0).firstChild.nodeValue;
	    if ( parseInt(inboxCount) != 0 ) 
	    	$('ul#toolbar li.mess a').text(inboxCount);
			
	    var friendInvitesCount = elem.getElementsByTagName('new-friend-invites-count').item(0).firstChild.nodeValue;
	    if ( parseInt(friendInvitesCount) != 0 ) 
	    	$('ul#toolbar li.friends a').text(friendInvitesCount);
    }
}

function fixValue(target_ell,h_ell_id)
{
    hidden_ell = document.getElementById(h_ell_id);
    has_photo = target_ell.checked;
    has_photo = has_photo ? 1 : 0;
    hidden_ell.value = has_photo;
    return true;
}


function sendPost(url, fileds)
{
	f = '';
	for( name in fileds )
	{
		f = f + '<input type="hidden" name="'+ name +'" value="'+fileds[name]+'"/>';
	}
	$('<form action="' + url + '" method="Post" style="display:none">'+f+'</form>').appendTo('body').submit();
}

function checkRow(el)
{
    cb = $(el).parents('tr').find( 'input@[type="checkbox"]' );
    cb.attr('checked', cb.attr('checked')?false:true );
}

function contestPlayer(id, link)
{
    var flashvars = {
        fullplaylist:'false',
        playlist: 'false',
        hplaylist: 'true',
        topbar: 'false',
        file: link
    };
    var params = {
        menu: "false",
        allowScriptAccess: "always",
        scale: 'noscale',
        allowFullScreen: 'true',
        bgcolor: "#000000",
        wmode: "opaque"
    };
    var attributes = {
        id:id + "_player"
    };

    document.getElementById(id).innerHTML = "<div id=\"" + id + "_del\"></div>";
    swfobject.embedSWF("design/flash/player.swf", id + '_del', "685", "373", "9.0.0", "design/flash/expressInstall.swf", flashvars, params, attributes);
}

$.fn.accordion = function() {
    var el = $(this[0]);
    
    if($.browser.msie) {
        var defOverflow = el.css('overflow');
        el.css('overflow', 'hidden');
    }

    maxHeight = el.height();

    if($.browser.msie) {
        el.css('overflow', defOverflow);
    }

    el.children('h3').each(function() {
        maxHeight -= $(this).outerHeight(true);
    });

    el.children('h3').next().each(function() {
        $(this).height(maxHeight).css({'overflow': 'auto'});
    });

    el.children('h3').click(function() {
        if ($(this).next().is(":hidden"))
        {
            el.children('h3').next().slideUp();
            $(this).next().slideDown();
            return false;
        }
    }).next().not(':first').hide();
}
$.fn.togleLink = function(selector,action){
	var selector = selector || false;
	var action = action || 'action';
	$(this).bind('click',function(event){
		var el = $(event.target);
		/*if(el.hasClass('show')){*/
			$(this).find('.hide').removeClass('hide').addClass('show');
			el.removeClass('show').addClass('hide');
		/*}*/
		if(selector){						
			$(selector).trigger(action);
		}
	});
}
$.fn.slideBox = function(){
	if($(this).css('display')=='none'){
		$(this)[0].display = false;
	}else{
		$(this)[0].display = true;
	}
	$(this).bind('action',function(){

		if($(this)[0].display){
			$(this)[0].display = false;
			$(this).slideUp('fast');;
		}else{
			$(this)[0].display = true;
			$(this).slideDown('fast');
		}
	});
}