function deletePodcast(podcastId) {
    if (confirm('Вы уверены, что хотите навсегда удалить этот подкаст?')) {
        document.location.href = '/user/delete.html?podcastId=' + podcastId;
    }
}
function lockInput(f, disable) {
    for (var i = 0; i < f.elements.length; i++) {
        if (f.elements[i].type == 'submit' && f.elements[i].name != 'cancel') {
            // skipping cancel submit so server-side cancel functionality works
            f.elements[i].disabled = disable;
        }
        else {
            f.elements[i].readOnly = disable;
        }
    }
    return true;
}
function lockSubmit(f, disable) {
    for (var i = 0; i < f.elements.length; i++) {
        if (f.elements[i].type == 'submit' && f.elements[i].name != 'cancel') {
            // skipping cancel submit so server-side cancel functionality works
            f.elements[i].disabled = disable;
        }
    }
    return true;
}
function openURL(link, url, internal) {
    if (internal) {
        location.href = url;
    } else {
        window.open(link, "_blank");
    }
}

function quickPlay(podcastId, rssFeedId, title, description, fileInfo, date,
		authorId, author, totalHits, rateIndex, downloadFileLink,
		download3gpLink, messageId, from, to, languages, userName,
		autoPlay, playBannerInfo, onCloseCode) {
    var elem = document.getElementById('player_popup');
    if (elem == null) {
        elem = document.createElement('div');
        elem.id = 'player_popup';
        hideElement(elem);
        document.body.appendChild(elem);
    }
    hideElement(elem);
    elem.innerHTML = createQuickPlayerHTML(podcastId, rssFeedId, title,
    		description, fileInfo, date, authorId, author, totalHits,
    		rateIndex, downloadFileLink, download3gpLink, messageId, from, to,
    		475, 375, languages, '', '', false, false,'onSite',null,'',
    		userName, autoPlay, playBannerInfo, onCloseCode);
    hideFlashes('player_popup');
    showElement(elem);
    positionElementAtScreenCenter(elem);
}

function closeQuickPlay(styleId, onCloseCode) {
    showFlashes();
    if (styleId != '') {
        return;
    }
    var elem = document.getElementById('player_popup');
    if (elem != null) {
        hideElement(elem);
        elem.innerHTML = '';
    }
    if (onCloseCode != null) {
    	eval(onCloseCode);
    }
}

function hideElement(elem) {
    elem.style.display = 'none';
}

function showElement(elem) {
    elem.style.display = 'block';
}

function positionElementAtScreenCenter(elem) {
	var viewportwidth, viewportheight;
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth, viewportheight = window.innerHeight;
	}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first
	// line in the document)
	else if (typeof document.documentElement != 'undefined'
			&& typeof document.documentElement.clientWidth != 'undefined'
			&& document.documentElement.clientWidth != 0) {
		viewportwidth = document.documentElement.clientWidth;
		viewportheight = document.documentElement.clientHeight;
	}
	// older versions of IE
	else {
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
		viewportheight = document.getElementsByTagName('body')[0].clientHeight;
	}
	
    var left = Math.round((viewportwidth - elem.offsetWidth) / 2);
    var top = Math.round((viewportheight - elem.offsetHeight) / 2);
    if (left < 0) left = 0;
    if (top < 0) top = 0;
    left += Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
    top += Math.max(document.documentElement.scrollTop, document.body.scrollTop);
    elem.style.left = left + 'px';
    elem.style.top = top + 'px';
}


function uploadPodcast(uForm) {
    uForm.target = "progress";
    progressBar.innerHTML = '<div class="loading_message_box"><img src="/i/loading.gif" alt=""/> Идет загрузка. Не закрывайте это окно ...</div>';
    lockInput(uForm, true);
    if (uForm.podcastId != null) {
        delpodcastlink.disabled = true;
    }
    return true;
}
function onPodcastUploaded(errors) {
    if (errors == null || errors.length == 0) {
        progressBar.innerHTML = '<div class="loading_message_box"><b>Видео успешно загружено. Переходим на список ...</b></div>';
        document.location.href = "/user/mypodcasts.html";
    }
    else {
        var errorsHtml = '<div class="message_box">';
        for (var i = 0; i < errors.length; i++) {
            errorsHtml += errors[i] + '<br/>';
        }
        errorsHtml += '</div>';
        progressBar.innerHTML = errorsHtml;
        lockInput(podcastForm, false);
        delpodcastlink.disabled = false;
    }

}

function buildFileInfo(podcastLength, contentTypeName) {
    var len;
    if (podcastLength < 1024) {
        len = '' + podcastLength;
    } else if (podcastLength < 1024 * 1024) {
        len = '' + Math.floor(podcastLength / 1024) + ' KB';
    } else {
        len = '' + Math.floor(podcastLength / (1024 * 1024)) + ' MB';
    }
    return len + ' / ' + contentTypeName;
}

function createQuickPlayerHTML(podcastId, rssFeedId, title, description, fileInfo,
		date, authorId, author, totalHits, rateIndex, downloadFileLink, download3gpLink,
        messageId, from, to, width, height, languages, server, styleId,
        isWidget, hideCloseBtn, pluginMode, videoListId, siteId, userName,
        autoPlay, playBannerInfo, onCloseCode) {
	return createQuickPlayerHTML0(podcastId, rssFeedId, title, description,
			fileInfo, date, authorId, author, totalHits, rateIndex, downloadFileLink, download3gpLink,
	        messageId, from, to, width, height, languages, server, styleId,
	        isWidget, hideCloseBtn, pluginMode,videoListId,siteId,
	        labelPlayInASeparatePage, labelRss, labelSizeType,
            labelAuthor, labelDate, labelFrom, labelTo,
            labelTotalViews, userName, autoPlay, playBannerInfo, onCloseCode);
}

function createQuickPlayerHTML0(podcastId, rssFeedId, title, description, fileInfo, date, authorId, author, totalHits, rateIndex, downloadFileLink, download3gpLink,
                               messageId, from, to, width, height, languages, server, styleId,
                               isWidget, hideCloseBtn, pluginMode,videoListId,siteId,
                               labelPlayInASeparatePage, labelRss, labelSizeType,
                               labelAuthor, labelDate, labelFrom, labelTo,
                               labelTotalViews, userName, autoPlay,
                               playBannerInfo, onCloseCode) {
	if (autoPlay == null) {
		autoPlay = false;
	}
    var isMessage = messageId != null;
    var viewUrl = isMessage ? ('/viewmessage.html?messageId=' + messageId)
            : '/podcast.html?podcastId=' + podcastId;
    viewUrl = server + viewUrl;
    var html = '';
    if (!hideCloseBtn) {
        html += '<div id="player_popup' + styleId + '_closebtn" onclick="closeQuickPlay(\'' + styleId + '\', \'' + onCloseCode + '\')"></div>';
    }
    else {
        html += '<div style="height:10px"></div>';
    }
    var flashVars = 'recordEnabled=false&amp;isVideo=true&amp;siteId=' + siteId + '&amp;streamName=' + podcastId + '&amp;languages=' + languages + '&amp;pluginMode=' + pluginMode + '&amp;videoListId=';
    if (userName != null && userName != '') {
    	flashVars += '&amp;userName=' + userName;
    }
    if (autoPlay) {
    	flashVars += '&amp;autoPlay=true';
    }
    if (playBannerInfo != null) {
    	flashVars += '&amp;' + constructBannerInfoFlashvars('play', playBannerInfo);
    }
    html += '<div id="player_popup' + styleId + '_player_col">';
    html += '    <div id="player_popup' + styleId + '_player">';
    html += '        <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" ';
    html += '            width="' + width + '" height="' + height + '" id="quickcast" align="middle">';
    html += '            <param name="allowScriptAccess" value="always" />';
    html += '            <param name="movie" value="' + server + '/quickcast/player.swf" />';
    html += '            <param name="flashvars" value="' + flashVars  + '" />';
    html += '            <param name="quality" value="high" />';
    html += '            <param name="allowfullscreen" value="true"/>';
//    html += '            <param name="wmode" value="transparent">';
    html += '            <param name="bgcolor" value="#ededed" />';
    html += '            <embed src="' + server + '/quickcast/player.swf"';
    html += '                quality="high" bgcolor="#ededed" width="' + width + '" height="' + height + '" name="quickcast" ';
    html += '                flashvars="' + flashVars  + '" allowfullscreen="true"';
    html += '                align="middle" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    html += '        </object>';
    html += '    </div>';
    if (!isWidget) {
        html += '    <div style="float: right;"><a href="javascript:openURL(null,\'' + viewUrl + '\',true)">' + labelPlayInASeparatePage + '</a></div>';
    }
    if (!isMessage) {
        for (var i = 0; i < rateIndex; i++) {
            html += '<img src="' + server + '/images/wstar.png" alt=""/>';
        }
    }
    html += '    <div class="pp_header">' + title + '</div>';
    html += '    <div class="pp_menu">';
    if (trim(download3gpLink).length > 0) {
    	html += '        <div>';
	    html += '        <div class="img" style="background-image: url(\'' + server + '/images/mobile_i.gif\');"></div>';
	    html += '        ' + download3gpLink;
	    html += '        </div>';
    }
    if (trim(downloadFileLink).length > 0) {
	    html += '        <div>';
	    html += '        <div class="img" style="background-image: url(\'' + server + '/images/file_i.gif\');"></div>';
	    html += '        ' + downloadFileLink;
	    html += '        </div>';
    }
    if (rssFeedId != -1) {
        html += '        <div>';
        html += '        <div class="img" style="background-image: url(\'' + server + '/images/rss_i.gif\');"></div>';
        html += '        <a href="' + server + '/rss/feed?feedId=' + rssFeedId + '">' + labelRss + '</a>';
        html += '        </div>';
    }
    html += '    </div>';
    html += '    <div class="pp_descr">';
    html += '        ' + labelSizeType + ':  <span>' + fileInfo + '</span>';
    html += '    </div>';
    html += '    <div class="pp_descr">';
    html += '        ' + labelAuthor + ': <span><a href="/showprofile.html?userId=' + authorId + '">' + author + '</a></span>';
    html += '    </div>';
    html += '    <div class="pp_descr">';
    html += '        ' + labelDate + ': <span>' + date + '</span>';
    html += '    </div>';
    if (isMessage) {
        html += '    <div class="pp_descr">';
        html += '        ' + labelFrom + ': <span>' + from + '</span>';
        html += '    </div>';
        html += '    <div class="pp_descr">';
        html += '        ' + labelTo + ': <span>' + to + '</span>';
        html += '    </div>';
    } else {
        html += '    <div class="pp_descr">';
        html += '        ' + labelTotalViews + ': <span>' + totalHits + '</span>';
        html += '    </div>';
    }
    html += '    </div>';
    return html;
}

function safeEncode(s) {
	return stringReplaceAll(Base64.encode(s), /\+/, '*');
}

function stringReplaceAll(str, regex, toWhat) {
    var oldStr;
    do {
		oldStr = str;
		str = str.replace(regex, toWhat);
    } while (oldStr != str);
    return str;
}

function constructBannerInfoFlashvars(prefix, bannerInfo) {
	var result = '';
	result += prefix + 'BannerLink=' + safeEncode(bannerInfo.link);
	result += '&amp;' + prefix + 'BannerType=' + bannerInfo.type;
	result += '&amp;' + prefix + 'BannerWidth=' + bannerInfo.width;
	result += '&amp;' + prefix + 'BannerHeight=' + bannerInfo.height;
	result += '&amp;' + prefix + 'BannerContent=' + safeEncode(bannerInfo.content);
	return result;
}

function overwriteStyles(styleSetId, styles) {
    var styleSet = document.getElementById(styleSetId);
    if (styleSet == null) {
        var head = getHeadElement();
        styleSet = document.createElement("style");
        styleSet = head.appendChild(styleSet);
        styleSet.setAttribute("type", "text/css");
    }
    var cssText = "";
    for (var i = 0; i < styles.length; i++) {
        cssText += styles[i] + "\n";
    }
    if (styleSet.styleSheet) {
        styleSet.styleSheet.cssText = cssText;
    }
    else {
        styleSet.appendChild(document.createTextNode(cssText));
    }
}
function getHeadElement() {
    var head = null;
    var headArr = document.getElementsByTagName("head");
    if (headArr.length == 0) {
        head = document.createElement("head");
        head = document.appendChild(head);
    }
    else {
        head = headArr[0];
    }
    return head;
}

function getPlayerStyles(styleSuffix, _player_bg_color, _player_captions_color, _player_text_color, _player_links_color, _player_font) {
    var styles = new Array();
    styles.push('div#player_popup' + styleSuffix + " {background-color:#" + _player_bg_color + "} ");
    styles.push('div#player_popup' + styleSuffix + "_player_col div.pp_header {color:#" + _player_captions_color + "} ");
    styles.push('div#player_popup' + styleSuffix + "_player_col div.pp_descr {color:#" + _player_captions_color + "} ");

    styles.push('div#player_popup' + styleSuffix + "_player_col div.pp_descr span {color:#" + _player_text_color + "} ");
    styles.push('div#player_popup' + styleSuffix + " a {color:#" + _player_links_color + "} ");
    styles.push('div#player_popup' + styleSuffix + " {font-family:" + _player_font + "} ");
    return styles;
}
function getVideoListStyles(styleSuffix, _videolist_bg_color, _videolist_border_color, _videolist_title_color, _videolist_text_color, _videolist_pages_color, _videolist_font) {
    var styles = new Array();
    styles.push(".bubbleVideoListContainer{background-color:#" + _videolist_bg_color + "; border:solid 1px #"
            + _videolist_border_color + ";font-family:" + _videolist_font + "} ");
    styles.push(".bubbletitle a{color:#" + _videolist_title_color + "} ");
//    styles.push("div#pageslist" + styleSuffix + " {background-color:#" + _videolist_bg_color + "} ");
    styles.push("div#pageslist" + styleSuffix + " a {color:#" + _videolist_pages_color + "} ");
    styles.push(".bubbledate {color:#" + _videolist_text_color + "} ");
    return styles;
}
function createCss(parentNode, src, id) {
    var css = document.getElementById(id);
    if (css == null) {
        css = document.createElement("link");
        css = parentNode.appendChild(css);
        css.setAttribute("id", id);
        css.setAttribute("rel", "stylesheet");
        css.setAttribute("media", "all")
        css.setAttribute("type", "text/css");
        css.setAttribute("href", src);
    }

}

function createScript(parentNode, src, id) {

    var js = document.getElementById(id);
    if (js == null) {
        js = document.createElement("script");
        js = parentNode.appendChild(js);
        js.setAttribute("type", "text/javascript");
        js.setAttribute("src", src);
        js.setAttribute("id", id);
    }
    return js;
}
function getDropdownValue(selName) {
    var sel = document.getElementById(selName);
    return sel.options[sel.selectedIndex].value;

}
function getRadioGroupValue(radioGroupName)
{
  var radioGroupObj = document.getElementById(radioGroupName);
  for (var i=0; i < radioGroupObj.length; i++)
    if (radioGroupObj[i].checked) return radioGroupObj[i].value;

  return null;
}
function copyToClipboard(id) {
    var elem = document.getElementById(id);
    if (elem != null) {
        elem.focus();
        elem.select();
//        if (elem.createTextRange) {
//           var range = elem.createTextRange();
//           if (range)
//             range.execCommand('Copy');
//         } else {
//           var flashcopier = 'flashcopier';
//           if(!document.getElementById(flashcopier)) {
//             var divholder = document.createElement('div');
//             divholder.id = flashcopier;
//             document.body.appendChild(divholder);
//           }
//           document.getElementById(flashcopier).innerHTML = '';
//           var divinfo = '<embed src="/swf/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(elem.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
//           document.getElementById(flashcopier).innerHTML = divinfo;
//         }
    }
}
function updatePlayerHTML(podcastId, rssFeedId, title, description, podcastLength,contentType, date, authorId, author, totalHits, rateIndex, downloadFileLink, download3gpLink,
                               width, height, languages, server, videoListId,siteId, userName) {
    var html = '';
    html += '<div id="player_popup_single_video">';
    html += createQuickPlayerHTML(podcastId, rssFeedId, title, description, buildFileInfo(podcastLength,contentType), date, authorId, author, totalHits, rateIndex, downloadFileLink, download3gpLink,
        null, null, null, width, height, languages, server, '_single_video', true, true, 'website',videoListId,siteId, userName);
    html += "</div>";
//    alert("updatePlayerHTML " + html);
    var vl = document.getElementById(videoListId);
    vl.innerHTML = html;
}

function proceedToViewPage(podcastId){
    document.location.href = '/podcast.html?podcastId=' + podcastId;
}

function changeFlashesVisibility(visible, idToIgnore) {
	var els = document.getElementsByTagName('object');
	for (var i = 0; i < els.length; i++) {
	    var el = els[i];
        var elToCheck = el;
        var found = false;
        while (elToCheck.parentNode != null && idToIgnore != null) {
            if (elToCheck.id == idToIgnore) {
                found = true;
                break;
            }
            elToCheck = elToCheck.parentNode;
        }
        if (!found || idToIgnore == null) {
            el.style.display = visible ? 'block' : 'none';
        }
	}
}

function showFlashes() {
	changeFlashesVisibility(true, null);
}

function hideFlashes(idToIgnore) {
	changeFlashesVisibility(false, idToIgnore);
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function trimLoginFormFields(form) {
	form.elements['j_username'].value = trim(form.elements['j_username'].value);
	form.elements['j_password'].value = trim(form.elements['j_password'].value);
}

function BannerInfo(link, type, width, height, content) {
	return {
		link: link, type: type, width: width, height: height, content: content
	};
}
