// console stub
window.console = window.console || {}
console.log = console.log || function(s){}
Prototype.Browser.Chrome = !!navigator.userAgent.match('Chrome');
Prototype.Browser.SVD = !!navigator.userAgent.match('SVD');
Prototype.Browser.IE9 = !!navigator.userAgent.match('Trident/5.0');
Prototype.Browser.FF = !!navigator.userAgent.match(/Firefox\/(\d+)\./);
Prototype.Browser.FFVersion = Prototype.Browser.FF ? Number(navigator.userAgent.match(/Firefox\/(\d+)\./)[1])  : -1;
Prototype.Browser.Windows = navigator.plarform ? navigator.platform.toLowerCase()=='win32' : !!navigator.userAgent.match(/win(32|dows)/i);
if (typeof isMini == 'undefined') isMini = false;
function SavevidAppletCookie() {
	document.cookie = "SavevidAppletCookie=1; path=/"
}
var path_url = "http://"+document.domain+"/";

function isPluginRequired() {
	return !isMini && Prototype.Browser.Windows && 
		(Prototype.Browser.Gecko || Prototype.Browser.IE) && 
		!Prototype.Browser.SVD /* && !Prototype.Browser.IE9*/
		&& !(Prototype.Browser.FF && Prototype.Browser.FFVersion>=5 )
}

/* Update counters values */
function updateCounters() {
	if (!$('counters')) return false;
	new Ajax.Request('/actions/getcounters.json?r='+Math.random(), {
		method: 'get',
		onSuccess: updateCountersPostExecution
	})
}

/* Update counters and latest videos on lastdownloads page */
function updateLastDownloads() {
	if (!$('list_last_down')) return false;
//	var d_limit = (typeof(window.limitDescr) == "undefined")?'':('&desc='+window.limitDescr)
//	var n_w = (typeof(window.newWindow) == "undefined")?'':('&nw='+(window.newWindow?'1':'0'))
	new Ajax.Request((window.lock_animation?'/actions/getcounters.json?r=':'/actions/getlastdownloads.json?timestamp=')+window.timestamp, {
		method: 'get',
		onSuccess: function(resp) {
			updateCountersPostExecution(resp);
			var obj = resp.responseJSON;
			for (i=0; i<obj['videos'].length; i++)
				if (obj['videos'][i]._timestamp > window.timestamp)
					window.videos_queue.push(obj['videos'][i]);
			window.timestamp = obj['timestamp'];
		}
	})
}

/* Refreshes queue of lastdownloads on the page */
function refreshLastDownQueue(){
	if (typeof(window.videos_queue) == "undefined") return false;
	if (window.lock_animation){
		setTimeout('refreshLastDownQueue()', window.period_download_update);
		return false;
	}
	if (window.videos_queue.length <= 0){
		setTimeout('refreshLastDownQueue()', window.period_download_update);
		return false;
	}
	while (window.videos_queue.length > window.queue_limit)
		window.videos_queue.shift();
	
	var element = window.videos_queue.shift();
	insertElementIntoLastdownQueue(element, 'refreshLastDownQueue()');
	
	return true
}

/*Start/stop animation on lastdownloads*/
function switchAnimation(){
	if (!$('pp-button')) return;
	window.limitActionCount = 0;
	$('pp-button').update('<img src="'+img_url+'/img/'+(window.lock_animation?'pause':'play')+'_sign.png" /><span>'+(window.lock_animation?'Pause':'Play')+'</span>');
	window.lock_animation = !window.lock_animation;
	$('pp-button').animation_locked = window.lock_animation;
}

function moveElWithEvent(el){
	Event.observe(el, 'click', function(event){
 		var element = Event.element(event).parentNode.parentNode.parentNode.parentNode.json_struct;
 		if (typeof element != "undefined") moveLastDownloadFirst(element);
 	});
}

function insertElementIntoLastdownQueue(element, skip) {
	
	var list_last_down = $('list_last_down')
	if (!list_last_down) return false
	
	var temp_date = new Date();
	var current_milliseconds = temp_date.getTime();
	if (typeof(window.last_list_update) != 'undefined' && skip != '' && current_milliseconds - window.last_list_update < window.period_download_update){
		//adding video is not in queue now, so add it to queue
		window.videos_queue.unshift(element);
		setTimeout(skip, window.period_download_update + window.last_list_update - current_milliseconds + 1);
		return false;
	}
	
	var snippets = list_last_down.childElements();
	var i;
	for (i=0; i<snippets.length; ++i){
		//updating downloaded ago time
		//$('lastdown-time-'+snippets[i].id.substr(12)).innerHTML = niceTime(window.timestamp - snippets[i].timestamp);
		//if such snippet exist and it's not adding by download click
		if (snippets[i].real_id == element.idvideo && skip != ''){
			setTimeout(skip, window.period_download_update);
			return false;
		}
	}
	
	if (typeof(window.limitAction) != "undefined" && skip != ''){
		if (typeof(window.limitActionCount) == "undefined") window.limitActionCount = 0;
		++window.limitActionCount;
		if (window.limitActionCount > window.limitAction){
			switchAnimation();
			window.videos_queue.unshift(element);
			setTimeout(skip, window.period_download_update);
			return false;
		}
	}
	
	window.timestamp += (typeof(window.last_list_update) != 'undefined')?parseInt((current_milliseconds - window.last_list_update)/1000):0;
	window.last_list_update = current_milliseconds;
	
	snippets = list_last_down.childElements();
	list_last_down.childElements()[0].className = list_last_down.childElements()[0].is_odd?'odd':'';
	if (snippets.length >= window.count_show){
		snippets[snippets.length - 1].json_struct = null;
		list_last_down.removeChild(snippets[snippets.length - 1]);
	}
	
	element.iclass = ' class="first' + (window.color?' odd':'') + '"';
	element.down = (parseInt(element.down) + 1) + '';
	var d_limit = (typeof(window.limitDescr) == "undefined")?400:window.limitDescr;
	if (element.htmldescription.length > d_limit) element.htmldescription = element.htmldescription.substr(0, d_limit - 3) + '...';
	if (typeof(window.img_sizes) != "undefined") element.imagesizes = 'width="'+window.img_sizes[0]+'" height="'+window.img_sizes[1]+'"';
	
	if (skip=='') 
		element.timeago = '<li id="lastdown-ago-'+element.idvideo+'" class="ldtimeago">' + niceTime(0) + '</li>';
	
	
	
	var template_vars = element;
	template_vars.starsrating = '';
	var text = window.template.evaluate(template_vars);
	window.color = !window.color;
	
	//if (skip=='') return true //quickfix by Vadim
	list_last_down.insert({top: text});
	
	
	var n_w = (typeof(window.newWindow) == "undefined")?true:window.newWindow;
	if (n_w) $$('#lastdown-id-'+element.idvideo+' a.watch-link').each(function(it){it.target = '_blank';});
	$$('#lastdown-id-'+element.idvideo+' a.downlink').each(function(it){moveElWithEvent(it);});
	
	var lastDown = $('lastdown-id-'+element.idvideo)
	
	lastDown.timestamp = (skip=='')?window.timestamp:element._timestamp;
	lastDown.real_id = element.idvideo;
	lastDown.json_struct = element;
	lastDown.is_odd = !window.color;
	lastDown.observe('mouseover', function(){window.lock_animation=true})
	lastDown.observe('mouseout', function(){if (!$('pp-button').animation_locked) window.lock_animation=false})
		
	$('lastdown-ago-'+element.idvideo).idvideo = element.idvideo;
	//for downloaded time ago .........
	$$('li.ldtimeago').each(function(it){it.innerHTML = niceTime(window.timestamp - $('lastdown-id-'+it.idvideo).timestamp);})
	
	var arr = ['downtoday', 'alldown']
	new Effect.Highlight(lastDown, {startcolor:'#eaf9ff', endcolor:'#ffffff', restorecolor:'#ffffff'})
	if ($('counters'))
		for (i=0; i<arr.length;i++) {
			var x = arr[i];
			var count = parseInt($(x).innerHTML);
			if (count < window.old_count_lastdown[x]) count = window.old_count_lastdown[x];
			$(x).innerHTML = count + 1;
			new Effect.Highlight($(x).parentNode, {startcolor:'#eaf9ff', endcolor:'#ffffff', restorecolor:'#ffffff'})
		}
	
	current_milliseconds = temp_date.getTime();
	setTimeout(skip, window.period_download_update + window.last_list_update - current_milliseconds + 1);
	return true;
}

function moveLastDownloadFirst(element){
	if (!$('list_last_down')) return true;
	
	var new_elem = element;
	snippets = $('list_last_down').childElements();
	var i;
	for (i=0; i<snippets.length; ++i)
		if (snippets[i].real_id == new_elem.idvideo){
			snippets[i].json_struct = null;
			$('list_last_down').removeChild(snippets[i]);
		}
	new_elem._timestamp = window.timestamp;
	insertElementIntoLastdownQueue(new_elem, '');
	if (!new_elem.down0) window.location = '#listtop';
	return true;
}

function niceTime(delta){
  if (delta < 60) {
	//return 'less than a minute ago';
	if (delta==1)
		return "1 second ago";
	return delta + " seconds ago";
  } else if (delta < 120) {
	return 'about a minute ago';
  } else if (delta < (45 * 60)) {
	return Math.floor(delta / 60) + ' minutes ago';
  } else if (delta < (90 * 60)) {
	return 'about an hour ago';
  } else if (delta < (24 * 60 * 60)) {
	return 'about ' + Math.floor(delta / 3600) + ' hours ago';
  } else if (delta < (48 * 60 * 60)) {
	return '1 day ago';
  } else {
	return Math.floor(delta / 86400) + ' days ago';
  }
}

/* Executed, when counters got, update counters on page */
function updateCountersPostExecution(resp) {
	if (!$('counters')) return false;
	var obj = resp.responseJSON
	var arr = ['watchedtoday', 'allwatch', 'downtoday', 'alldown'];
	for (i=0; i<arr.length;i++) {
		var x = arr[i];
		if ((x == 'downtoday' || x == 'alldown') && typeof(window.count_lastdown) != "undefined"){
			window.old_count_lastdown[x] = parseInt(window.count_lastdown[x]);
			window.count_lastdown[x] = obj['counter'][x];
		}else{
			if ($(x).innerHTML == obj['counter'][x]) continue;
			$(x).innerHTML = obj['counter'][x];
			new Effect.Highlight($(x).parentNode, {startcolor:'#eaf9ff', endcolor:'#ffffff', restorecolor:'#ffffff'});
		}
	}
}

function isEmail(str) {
	return /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.([a-z]){2,4})$/.test(str)
}

function toolbarShow(callbackFunc) {
	callbackFunc = callbackFunc || Prototype.emptyFunction
	if ($('b-div')) {//already shown toolbar
		callbackFunc()
	} else {
		new Ajax.Request('/actions/template.php', {
			method:'get',
			parameters: {type: 'toolbar-offer'},
			onSuccess: function(resp){
				$(document.body).insert(resp.responseText)
				toolbarAd = new classAd({
					container:'b-div',
					closeBtn: '#t-close-btn, .t-close-btn',
					callback: callbackFunc,
					overlay: true
				})
				toolbarAd.show()
			},
			onFailure: callbackFunc
		})
	}
	return false
}

function watchPageDownload(link, video) {
	if (link.innerHTML != undefined)
        _gaq.push(['_trackEvent', 'WatchPage', link.innerHTML.stripTags()]);

    $('l-container').insert({bottom:new Element('ul', {
        'class': 'download-links link-list bgwhite',
        'style': 'display:none'
    })});
    var downloader = new WatchPageVideoDownloader({container:$$('.download-block')[0]});
    downloader.setVideoObj(video);
    downloader.download(downloader.$('down-box-v-links'));
	return false
}


/**
 * Does nothing, if was uploaded already
 * @param container
 * @param callback
 */
function getTemplate(options) {
    var uploader = new TemplateUploader(options);
    uploader.request();
}

var TemplateUploader = Class.create({
    /**
        Instance methods
        @var Element
        container: null,

        @var string
        type: null,

        @var function
        callback: null,
    */
	callbacks: [],
	uploaded: {},
	in_progress: {},
    containers: [],
    initialize: function(options) {
        this.type = options.type;
        this.container = options.container;
        if (!this.callbacks[this.type]) {
            this.callbacks[this.type] = [];
        }

        if (!this.containers[this.type]) {
            this.containers[this.type] = [];
        }
        this.callback = options.callback;
    },
    request: function() {
        //add to the queue
        this.observe(this.callback, this.container);
        
        switch (true) {
            case typeof this.uploaded[this.type] != 'undefined':
                this.downloaded(this.uploaded[this.type]);
            case this.in_progress[this.type]:
                return;
        }
        this.in_progress[this.type] = true;
        new Ajax.Request('/actions/template.php?type=' +this.type, {
            method: 'get',
            onSuccess: function(resp){
                this.downloaded(resp.responseText);
            }.bind(this)
        });
    },
    observe: function(callback, container) {
        this.callbacks[this.type].push(callback || Prototype.emptyFunction);
        this.containers[this.type].push(container);
    },
    downloaded: function(resp){
        this.containers[this.type].each(function(container) {
            $(container).update(resp);
        });
        this.uploaded[this.type] = resp;
        this.callbacks[this.type].each(function(callback){
            //callback if needed
            callback()
        });
        this.callbacks[this.type] = [];
        this.in_progress[this.type] = 0;
    }
})

/**
    Class used for calling function, only when several async requests are finished. Usage:
    va exampleCombo = new Combo(finalFunction, 3)
    asyncFunction(exampleCombo.add())
    asyncFunction(exampleCombo.add())
    asyncFunction(exampleCombo.add())
    ....
    When all asynFunctions are finished finalFunction will be called
 */
var Combo = Class.create({
    finishedHandler: null,
    length: 0,
    callbacks: [],
    initialize: function(finishedHandler, operationsCount){
        this.setHandler(finishedHandler);
        this.length = operationsCount || 0;
    },
    setHandler: function(handler) {
        this.finishedHandler = handler;
    },
    add: function(callback){
        var self = this;
        var _callback = (callback || Prototype.emptyFunction);
        return function(){
            self.finishedOne()
            _callback.apply(null, arguments)
            if (self.isFinished()) {
                self.finishedHandler()
            }
        }
    },
    finishedOne: function(){
        this.length--;
    },
    isFinished: function() {
        return this.length == 0;
    }
})

function bytes2Mb(bytes){
    var res;
    if (bytes != 0 && bytes >0 ) {
        res = (bytes / 1024 / 1024 * 100 ).round() / 100 + 'Mb';
    }

    return res;
}

function prepareDetection() {
    var progress = new ProgressIndicator({container:$('downloads-container'), place: 'top'});
    progress.loading();
    $$('.download-e').invoke('removeClassName', 'hidden');
    $$('.download-container').invoke('remove');
    return progress;
}

//TODO move out common part
function miniDownload(e) {
    if (e) e.stop();

    _gaq.push(['_trackEvent', 'DownloadBox', 'ButtonClick', 'Conduit']);
    
    $('url').value = $F('url').replace($('url').title, '').replace(/ /g, '');
    $('url').value = myCompareStrings($('url').value, $('url').title, true);

    if ($('url').value == '') {
        urlOnBlur.apply($('url'))
        return false
    }

    var link = $F('url');

    var progress = prepareDetection();

    elem = new Element('div', {
        id: 'download-repeat' ,
        'class': 'download-container'
    });
    $('downloads-container').insert({bottom:elem});
    var detector = new DownloadBoxVideoDetector({
        container: elem,
        link: link,
        callbackDetected: progress.finished.bind(progress),
        callbackError: progress.finished.bind(progress)
    });
    detector.fetch();
}

/**
    Opens page in hidden iframe. Useful for file downloads and tracking events in the meantime
*/
function separateDownload(elem){
    var iframe = new Element('iframe', {
        src: elem.getAttribute('href'),
        frameborder: 0,
        width: '0px',
        height: '0px'
    });
    $(document.body).insert(iframe);
}

function runDownload() {
    _gaq.push(['_trackEvent', 'DownloadBox', 'ButtonClick']);
	
    $('url').value = $F('url').replace($('url').title, '').replace(/ /g, '');
    $('url').value = myCompareStrings($('url').value, $('url').title, true);

    if ($('url').value == '') {
        urlOnBlur.apply($('url'))
        return false
    }

    if ($('page-main-banner')) $('page-main-banner').update('');
    if ($('page-video-banner')) $('page-video-banner').update('');

//   links = ['http://www.metacafe.com/watch/5278635/amphibious_car/', 'http://www.youtube.com/watch?v=SSd_DbWzbVc', 'http://www.youtube.com/watch?v=niqrrmev4mA', 'http://www.youtube.com/watch?v=B7ZUHbLHMBs'];
//    links = [$F('url')];
    links = $F('url').split("\n");

    var container = $('downloads-container'), 
        detectors = {};

    var progress = prepareDetection();
    videosFetch = new Combo(progress.finished.bind(progress), links.length);
    for (var i=0; i < links.length; i++) {
        var link = links[i];
        elem = new Element('div', {
            id: 'download-repeat' + i,
            'class': 'download-container'
        });
        container.insert({bottom:elem});
        detectors[link] = new MainPageVideoDetector({
            progressIndicator: progress.indicator,
            container: elem,
            link: link,
            callbackDetected: videosFetch.add(),
            callbackError: videosFetch.add()
        });
        detectors[link].fetch();
    }

    return false
}

var ContainerTraverse = Class.create({
    defaultOptions: $H({
        /**
            @var Element
         */
        container: null
    }),
    initialize: function(options) {
        this.options = this.defaultOptions.merge(options).toObject();
    },
    $: function(id) {
        if (id) {
            return this.options.container.select('.' + id)[0];
        } else {
            return this.options.container;
        }
    },
    $$: function(selector) {
        return this.options.container.select(selector);
    }
});

/**
    Class with common methods for video download
*/
var VideoDownloaderNormal = Class.create(ContainerTraverse, {
    /**
        Instance properties
        @var DownloadClass object
        downloader: null,

        @var Object
        video: null,
    */
    setVideoObj: function(video) {
        this.video = video;
    },
    download: function(downloadContainer) {
        this.downloader = new DownloadClass({container: downloadContainer, root: this.$() });
        this.downloader.errorNoJava = this.errorNoJava();
        this.downloader.setVideo(this.video);
        this.downloader.setProvider(this.downloader.detectProvider());
        this.downloader.setRetryCallback(this.download.bind(this, downloadContainer));
        this.downloader.doDownload(this.downloadFinished.bind(this));
        return false;
    },
    downloadFinished: function() {
        this.downloader.showButtons();
    },
    videoUrl: function(){
        return '#';
    },
    errorNoJava: function(){
        return 'To download this video, you need to install the Java plug-in. <a href="'+deployJava.getJavaURL+'" target="_blank">Click here</a> to install the Java plug-in. After the installation is complete, <a href="'+this.videoUrl()+'">click here</a> to reload this page.';
    }
});

VideoDownloaderPlugin = Class.create(VideoDownloaderNormal, {
    form: null,
    formFinished: null,
    download: function($super, downloadContainer) {
        this.showForm({
            container: downloadContainer,
            onSuccess: function() {
                this.form.addClassName('hidden');
                $super(downloadContainer);
            }.bind(this)
        });
//        $super(downloadContainer);
        return false;
    },
    showForm: function(options) {
        this.form = this.$('d-plugin-form');
        this.formFinished = this.form.clone();
        var progress = new ProgressIndicator({container: this.form, place:'before'});
        progress.loading();
        var combo = new Combo(null, 2);
        getTemplate({
            type: 'dp-started',
            container: this.formFinished,
            callback: combo.add()
        });

        var form = this.form;
        var formFinished = this.formFinished;
        var self = this;

        getTemplate({
            type: 'd-plugin-form',
            container: this.form,
            callback: function() {
                progress.finished();
                $('download-button').observe('click', function(e){
                    e.stop();
                    _gaq && _gaq.push(['_trackEvent', 'SavevidPluginV1', 'DownloadClick']);
                    separateDownload(e.findElement());
                    self.notify();
                    combo.setHandler(function(){
                        form.update(formFinished.innerHTML);
                    });
                    combo.add()();
                });
                $('d-continue').observe('click', function(e) {
                    e.stop();
                     _gaq && _gaq.push(['_trackEvent', 'SavevidPluginV1', 'SkipClick']);
                    (options.onSuccess || Prototype.emptyFunction)();
                });
                this.form.removeClassName('hidden');
                _gaq && _gaq.push(['_trackEvent', 'SavevidPluginV1', 'DownloadShow']);
            }.bind(this)
        });
    },
    notify: function() {
        new Ajax.Request('/actions/plugin-downloaded', {
            method: 'get',
            parameters: {url: this.videoUrl()}
        });
    }
});

VideoDownloader = isPluginRequired() ? VideoDownloaderPlugin : VideoDownloaderNormal;

/**
* Class is used on watch page
*/
var WatchPageVideoDownloader = Class.create(VideoDownloader, {
    download: function($super, downloadContainer) {
	    this.$('download-status').update('Please wait');
        if (this.video.requiresApplet) {
    	    this.$('download-details')
                .update('<p class="bold padT10" style="text-align:center;">To download Youtube videos you should click &quot;Run&quot; when java window opens.<br /> Enable &quot;Always trust content from the publisher&quot; to download seamlessly in the future.</p>')
                .removeClassName('hidden');
        } else {
    	    this.$('download-details').update().addClassName('hidden');
        }
        downloadContainer.removeClassName('hidden');
        this.$('download-first').hide();
//        this.progress = new ProgressIndicator({container: this.$(), place: 'bottom'});
//        this.progress.loading();
//        downloadContainer.removeClassName('hidden');
        $super(this.$('d-links'));
//        $super($$('.download-block')[0]);
    },
    downloadFinished: function($super) {
        $super();
//        this.progress.finished();
        this.$('download-status').update('Available video formats');
    },
    videoUrl: function() {
        return path_url + this.video.downbox_watch_link;
    }
});

var VideoDetector = Class.create(VideoDownloader, {
    errorUnableToSave: 'Unable to save video. Retry',
    defaultOptions: $H({
        link: '',
        container: null,
        callbackDetected: Prototype.emptyFunction,
        callbackFetched: Prototype.emptyFunction
    }),
    initialize: function($super, options) {
        $super(options);
        //TODO function should accept multiple callbacks
        this.functionAdd = Math.round(Math.random() * 1000);
    },
    globalFunctionWrapper: function(name, func) {
        return globalFunctionWrapper(name + this.functionAdd, func);
    },
    detectError: function(message) {
        this.options.callbackError(message);
        return message;
    },
    fetch: function() {
        new Ajax.Request('/actions/getvideo.json', {
            method: 'post',
            parameters: {
                url: this.options.link,
                r: Math.random()
            },
            onSuccess: function(response){ 
                return this.videoResult(response.responseJSON);
            }.bind(this)
        });
    },
    videoResult: function(result) {
        if (result['error'] == 0){
            this.normalDownload(result);
        }else{
            switch (result['error']) {
                case -200:
                    this.xmlDownload(result);
                    break;
                case -400:
                    this.javaDownload(result);
                    break;
                default:
                    this.detectError(result['message']);
            }
        }
    },
    downloadFinished: function() {
        var shown = this.downloader.showButtons();
        if (!shown) return;
        this.options.callbackFetched();
        return shown;
    },
    xmlDownload: function(result) {
        this.options.callbackDetected();
        return;
    },
    javaDownloaded: function(video) {
        var tags = video.tags,
            category = video.category;
        delete video.tags;
        delete video.category;
        video = $H(video)
            .merge(this.video)
            .toQueryString();
        video = video + '&categories[]=' + encodeURIComponent(category);
        tags.each(function(tag){
            video = video + '&tags[]=' + encodeURIComponent(tag);
        });
        //save video to db
        var self = this;
        new Ajax.Request('/actions/setvideo.php', {
            method:'post',
            parameters: video,
            onSuccess: function(response){
                resp = response.responseJSON;
                if (resp.error != 0) {
                    self.detectError(self.errorUnableToSave);
                    return;
                }
                resp.links = self.video.links;
                self.normalDownload(resp);
            },
            onFailure: function(){
                self.detectError(self.errorUnableToSave);
            }
        });
    },
    javaDownload: function(result) {
        this.setVideoObj(result);
        try {
			//console.log(result)
        var combo = new Combo(Prototype.emptyFunction, 2),
            self = this,
            errorFunc =  this.globalFunctionWrapper('detectError', function(error){
                self.detectError(error);
            }),
            applet = new JavaApplet($H({
                mayscript: 'true',
                code: 'SavevidApplet2.class',
                codebase: '/',
                archive:  typeof(useJavaApplet) == 'undefined' ? 'savevid.jar' : useJavaApplet,
                url: result.url,
								ua: navigator.userAgent,
                onVideoInfo: this.globalFunctionWrapper('javaDownloaded' , combo.add(function(resp){
                    combo.setHandler(self.javaDownloaded.bind(self, new String(resp).evalJSON()));
                })),
                onSuccess: this.globalFunctionWrapper('linksDetected', combo.add(function(links){
                    self.video.links = new String(links).evalJSON();
                })),
                onError:errorFunc,
                onRetry: errorFunc,
                notifyUrl: path_url + 'actions/ytfmt.php'
            }));
            applet.start();
        } catch (e) {
            this.detectError(this.errorNoJava());
        }
    },
    /**
        Public method, can be overwritten by children
     */
    normalDownload: function(result) {
        this._normalDownload(result);
    },
    _normalDownload: function(result) {
        this.setVideoObj(result);
        this.download(this.$('l-container'));
    },
    download: function($super, downloadContainer) {
        this.options.callbackDetected();
        return $super(downloadContainer);
    }
});

var DownloadBoxVideoDetector = Class.create(VideoDetector, {    
    initialize: function($super, options){
        $super(options);
        this.progressIndicator = options.progressIndicator;
    },
    fetch: function($super) {
        var videoCombo = new Combo(function(){}, 2);
        getTemplate({
            type: 'download-repeat',
            container: this.$(),
            callback: videoCombo.add()
        });
        this.videoResult = this.videoResult.wrap(videoCombo.add(function(callOriginal, response){
            videoCombo.setHandler(callOriginal.bind(this, response));
        }.bind(this)));
        return $super();
    },
    downloadFinished: function($super) {
        var shown = $super();
        if (!shown) return;
        this.$('download-status').update('Finished!');
        this.$('formats-desc').update(shown + ' formats available');
        return shown;
    },
    download: function($super, downloadContainer) {
        var videoLink = new Element('a', {
            target: '_blank',
            href: this.video.url
        });
        this.$('down-box-v-title').update(videoLink.clone().insert('&gt; ' + this.video.title));
        this.$('formats-desc').update('Detecting formats');
        return $super(downloadContainer);
    },
    normalDownload: function($super, result) {
        this.$('download-links').hide();
        this.$('thumb').update(new Element('a', {
            target: '_blank',
            href: result.url
        }).update('<img src="'+ result.json_struct.thumb +'" width="74px" />'));

        this.$$('.download-links .watch').invoke('remove');
        this.$('formats-desc').update('Detecting formats');

        result['json_struct'].down0 = true;
        new BookmarkClass(result['bloglinks'], {container:this.$()}).change('direct');

        this.$('input_blog_link').value = result['bloglinks']['direct'];
        this.$('share-links').show();
        this.$('d-progress').addClassName('hidden');
        this.$('down-box-v-links').removeClassName('hidden');
        return $super(result);
    },
    javaDownloaded: function($super, video){
        this.progressIndicator.previous().remove();
        $super(video);
    },
    javaDownload: function($super, result) {
        this.progressIndicator.update('Launching Applet')
            .insert({before:'<p class="bold applet-warning padT10" style="text-align:center;">To download Youtube videos you should click &quot;Run&quot; when java window opens.<br /> Enable &quot;Always trust content from the publisher&quot; to download seamlessly in the future.</p>'});
        this.detectError = this.detectError.wrap(function(callOriginal, header, message){
            this.progressIndicator.previous().remove();
            callOriginal.apply(this, Array.prototype.slice.call(arguments, 1));
        }.bind(this));
        $super(result);
    },
    xmlDownload: function($super, result) {
        var info = result['message'];
        this.$('down-box-v-title').update(info['title']);
        this.$('download-links').innerHTML = '';
        var li_for_link = new Element('li')
        this.$('download-links').appendChild(li_for_link.addClassName('bg-none')
                .update('<a class="downlink" href="'+info['url']+'">Download</a>'))
        this.$('share-links').hide()
        this.$('down-box-v-links').removeClassName('hidden');
        this.$('spinner').hide();
        this.$('download-status').update('Finished');
        this.$('formats-desc').update('Detected 1 format');
        this.$().removeClassName('hidden');
        return $super(result);
    },
    detectError: function($super, message) {
        this.$('detect-error').select('p')[0].update(message)
        this.$('detect-error').removeClassName('hidden');
        this.$().addClassName('operations-error');
        return $super(message);
    }
});

var MainPageVideoDetector = Class.create(DownloadBoxVideoDetector, {
    download: function($super, downloadContainer) {
        if (this.video.requiresApplet) {
            this.$('download-details').update('To download Youtube videos you should click &quot;Run&quot; when java window opens.<br /> Enable &quot;Always trust content from the publisher&quot; to download seamlessly in the future.').removeClassName('hidden');
        } else {
            this.$('download-details').update().addClassName('hidden');
        }
        return $super(downloadContainer);
    },
    downloadFinished: function($super) {
        var shown = $super();
        if (!shown) return;
        if (!this.video.adult) {
            this.$('download-links').appendChild(new Element('li',{'class': 'watch'})
                .update('<a href="'+path_url+this.video['downbox_watch_link']+'"><span class="d-button">Watch</span><h4>Watch</h4></a>'));
        }
        return shown;
    },
    videoUrl: function() {
        if (this.video)
            return path_url + '?url=' + encodeURIComponent(this.video.url);
        else 
            return path_url;
    }
});

var ProgressIndicator = Class.create(ContainerTraverse, {
    /**
        Instance properties
        place to add loading text
        options.place bottom, top

        Progress indicator
        @var Element
        indicator
    */
    loading: function() {
        this.indicator = new Element('div', {'class': 'v-loading loading-text'}).update('Loading, please wait...');
        var opts = {};
        opts[this.options.place] = this.indicator;
        this.$().insert(opts);
    },
    finished: function() {
        this.indicator.remove();
    }
});

var Downloadable = Class.create(ContainerTraverse, {
    /**
        Instance properties
        @var function
        retryCallback: undefined,
        root: container of the download class
    */
    initialize: function($super, options) {
        $super(options);
        this.errorIE9 = 'We are sorry, the browser you are using is not yet supported by Savevid.';
        this.errorNoLinks = 'No download links were found for the selected video.';
        this.errorPermissions = 'This video cannot be downloaded because of its permission settings.';
        this.root = new ContainerTraverse({container:options.root});
        this.root.$('download-error').update().addClassName('hidden');
    },
    downloadError: function(header, message, doReport) {
        if (arguments.length == 1) {
            message = header;
            header = 'Error occured while downloading';
        }
        this.getErrorTemplate(function() {
                var container = new ContainerTraverse({container:this.root.$('download-error')});
                container.$('err-text').update(message);
                /**
                    @deprecated
                */
                if (0 && typeof this.retryCallback != 'undefined') {
                    message += '. ';
                    //TODO bind retryCallback to current class
                    var retryButton = new Element('a', {
                        'class':'download-retry',
                        href: '#'
                    }).update('Retry?').observe('click', function(e){
                        e.stop()
                        this.retryCallback()
                    }.bind(this));
                    container.$('err-text').update(message).insert({bottom: retryButton});
                }
                container.$().removeClassName('hidden');
                this.root.$('download-status').update(header).addClassName('warning');
                if (this.$('formats-desc')) {
                    this.$('formats-desc').update('No formats available for download');
                }
                this.$('spinner').addClassName('hidden');
                this.root.$('download-details').update().addClassName('hidden');
                if (doReport == true && this.video.id_video && message) {
                    //notify server that video should be hidden
                    new Ajax.Request('/actions/download_error.php', {
                        method: 'get',
                        parameters: {
                            id_video: this.video.id_video,
                            reason: message,
                            sig: this.video.signature
                        }
                    });
                }
        }.bind(this));
    },
    //use it, if template becomes very complicated
//    getErrorTemplate: function(callback) {
//        getTemplate({
//            type: 'download-error',
//            container: this.root.$('download-error'),
//            callback: (callback || Prototype.emptyFunction)
//        });
//    },
    getErrorTemplate: function(callback){
        this.root.$('download-error').update('<p class="err-text"></p>');
        (callback || Prototype.emptyFunction)();
    },
    setRetryCallback: function(retry) {
        this.retryCallback = retry;
    }
});

var DownloadClass = Class.create(Downloadable, {
    /**
        Instance properties
        @var object
        video: null,

        @var ProviderClass
        provider: null,
    */
    initialize: function($super, options) {
        //null object
        $super(options);
        this.provider = new ProviderClass({root: $$('body')[0], video:1});
        this.downloadError = this.downloadError.wrap(function(callOriginal, header, message) {
            //provide human-readable error
            var args = Array.prototype.slice.call(arguments, 1);
            if (this[header])
                args[0] = this[header]

            callOriginal.apply(this, args);
        }.bind(this));
    },
    setProvider: function(provider) {
        this.provider.stopPrevious();
        this.provider = provider;
    },
    setVideo: function(video) {
        this.video = video;
    },
    /**
        Detects provider based on this.video
        @uses this.video       
     */
    detectProvider: function() {
        var defaultParams = {
            container: this.$(),
            root: this.root.$(),
            video: this.video,
            onError: this.downloadError.bind(this),
            onRetry: function(){
                this.setRetryCallback(undefined);
                this.downloadError.apply(this, arguments);
            }.bind(this)
        };
        switch (true) {
            case typeof this.video.links != 'undefined':
                return new MockProviderClass($H(defaultParams).merge({
                    links:this.video.links
                }).toObject());
            case this.video.requiresApplet:
                return new JavaAppletProviderClass(defaultParams);
            default:
                return new GenericProviderClass(defaultParams);
        }
    },
    preview: function() {
        switch (window.location.hash) {
            case '#IE9':
                return 'errorIE9';
            case '#no-links':
                return 'errorNoLinks';
            case '#java-denied':
                return 'Permission denied';
            case '#no-java':
                return 'errorNoJava';
            default:
                return null;
        }
    },
    setRetryCallback: function($super, handler) {
        $super(handler);
        if (typeof this.provider != undefined)
            this.provider.setRetryCallback(handler);
    },
    doDownload: function(resHandler){
        this.$().removeClassName('hidden');
        this.$('spinner').removeClassName('hidden');
        if (text = this.preview()) {
            this.setRetryCallback(undefined);
            this.downloadError(text);
            return;
        }
        /*if (Prototype.Browser.IE9) {
            this.setRetryCallback(undefined);
            this.downloadError('errorIE9');
            return;
        }*/
		//$('down-box-v-links').removeClassName('hidden');
		this.root.$('download-status').removeClassName('warning')
		this.$('spinner').removeClassName('download-error').update();

        if (this.$('download-links').visible()) {
            this.$('download-links').fade({duration:0.1,afterFinish:function(){this.$('spinner').show()}.bind(this)});
        } else {
            this.$('spinner').appear();
        }

		this.provider.setHandler(resHandler || this.showButtons.bind(this));
        this.provider.getDownloadLinks()

	},
    showButtons: function() {
        if (typeof this.video == "undefined" ) {
            throw "Video object not found";
        }
        this.root.$('download-details').update().addClassName('hidden');
        var shown = this.provider.showButtons();
        if (!shown) {
            delete this.retryCallback;
            this.downloadError('errorNoLinks');
        }

        return shown;
    }
});

ProviderClass = Class.create(ContainerTraverse, {
    /**
        @var object
        video: null,

        @var function
        handler: null,

        @var function
        onError: null
    */
    initialize: function($super, options) {
        $super(options);
        this.video = options.video;
        this.data = new Hash();
        this.onError = options.onError || Prototype.emptyFunction;
        this.onRetry = options.onRetry || Prototype.emptyFunction;
        this.retryCallback = Prototype.emptyFunction;
        this.root = new ContainerTraverse({container: options.root});
    },
    setHandler: function(handler) {
        this.handler = handler;
    },
    showButtons: function(){},
    getDownloadLinks: function() {},
    stopPrevious: function() {},
    setData: function(data){
        this.data = this.data.merge(data);
    },
    getData: function(value) {
        return this.data.get(value);
    },
    setRetryCallback: function(callback) {
        this.retryCallback = callback;
    }
})

GenericProviderClass = Class.create(ProviderClass, {
    /**
        Instance properties
        @var string
        signature: null,

        @var object
        downloadLinks: null,
    */
    initialize: function($super, options) {
        $super(options);
        this.combo = new Combo(null, 3)
        getTemplate({
            type: 'download-links',
            container: this.$('download-links'),
            callback: this.combo.add()
        })
        this.setLinks = this.combo.add(this._setLinks.bind(this))
    },
    setHandler: function($super, handler) {
        $super(handler);
        this.combo.setHandler(handler);
    },
	getSignature: function(video){
        var self = this;
		new Ajax.Request('/actions/video_signature.php', {
			method:'get',
			parameters: {nocache: Math.random(), id_video: this.video.id_video},
			onSuccess: this.combo.add(function(resp){
				var r = resp.responseJSON;
				self.signature = r;
			}),
			onFailure: function(){
				self.onError('Download error', 'Please reload the page and retry');
			}
		});
	},
    getDownloadLinks: function() {
		this.getSignature();
		this.root.$('download-status').update('Found!');
        this._getDownloadLinks(this.video.id_video);
    },
    _getDownloadLinks: function(id_video) {
		new Ajax.Request('/actions/ddown.php?id=' + id_video, {
			method: 'post',
			onSuccess: function(resp) {
				$(document.body).style.cursor = 'default';
				var response = resp.responseJSON;
				if( response.error == 0 ){
					if (typeof response.message == "object") {
						this.setLinks(response.message);
					} else {
						window.location = response.message;
					}
				} else {
					this.onError(response.message);
					/*new Effect.Highlight($('response'), {startcolor:'#eaf9ff', endcolor:'#ffffff', restorecolor:'#ffffff'});*/
					/*
					* @deprecated
					$('captcha_form').observe('submit',function (){
						event.stop();
						return doDownload(this);
					}.bind(this));
					*/
				}
			}.bind(this)
		});

    },
    /**
        function will be called from combo stack
     */
	_setLinks: function(links){
        this.downloadLinks = links;
	},
    showButtons: function(){
        var links = this.downloadLinks,
            video = this.video;
        var shown = $H(links).size();
				//console.log(links)
        this.$$('.d-link').each(function(li){
            var fmtId = li.className.substr(12) //strip dbutt
            if ( typeof links[fmtId] != 'undefined' ) {
                //detect whether it is simple link or with size
                switch (true) {
                    case typeof links[fmtId] == 'string':
                        var url = links[fmtId];
                        var size = 'unknown';
                        break;
                    case typeof links[fmtId][1] == 'undefined':
                        var url = links[fmtId][0];
                        var size = 'unknown';
                        break;
                    default:
                        var url = links[fmtId][0];
                        var size = bytes2Mb(links[fmtId][1]);
                }
                li.down('a')
                    .writeAttribute('href', '/actions/download.php?id=' + video.json_struct.idvideo + '&id_format=' + fmtId+ '&url=' + encodeURIComponent(url) + '&signature=' + this.signature.signature + '&t='+this.signature.t)
                    .observe('click', function(e){
                        var elem = e.findElement('a'), 
                            format = elem.select('.d-button')[0].innerHTML;
                        format = format + ' ' + elem.select('.d-title h4')[0].innerHTML;
                        _gaq.push(['_trackEvent', 'VideoDownload', format]);
                    });
                this.$('dbutt-size' +fmtId).update(size);
                li.show();
            } else {
                li.hide();
            }
        }, this)

        this.$('spinner').fade({afterFinish:function(){
            this.$('download-links').show();
        }.bind(this)});

        return shown;
    }
})

MockProviderClass = Class.create(GenericProviderClass, {
    initialize: function($super, options) {
        $super(options);
        this.links = options.links;
    },
    _getDownloadLinks: function() {
        this.setLinks(this.links);
    }
});

JavaAppletProviderClass = Class.create(GenericProviderClass, {
    /**
        Instance properties
        @var string
        functionAdd: '',
    */
    initialize: function($super, options) {
        $super(options);
        //TODO function should accept multiple callbacks
        this.functionAdd = Math.round(Math.random() * 1000);
    },
    globalFunctionWrapper: function(name, func) {
        return globalFunctionWrapper(name + this.functionAdd, func);
    },
    getDownloadLinks: function() {
		this.getSignature();
		this.root.$('download-status').update('Loading java applet.');
	    this.javaAppletLoad({
            onSuccess: this.globalFunctionWrapper('setLinks', this.setLinks.bind(this)),
            onError: this.globalFunctionWrapper('onError', this.onError),
            onRetry: this.globalFunctionWrapper('onRetry', this.onRetry),
            retryFunction: this.globalFunctionWrapper('retryFunc', this.retryCallback)
		});
    },
    javaAppletLoad: function(customAppletParams) {
        try {
            var applet = new JavaApplet($H({
                mayscript: 'true',
                code: 'SavevidApplet2.class',
                codebase: '/',
                archive:  typeof(useJavaApplet) == 'undefined' ? 'savevid.jar' : useJavaApplet,
                url: this.video.url,
								ua: navigator.userAgent,
                id_video: this.video.id_video,
                onSuccess: 'Prototype.emptyFunction',
                onError: 'Prototype.emptyFunction',
                onRetry: 'Prototype.emptyFunction',
                retryFunction: 'Prototype.emptyFunction',
                notifyUrl: path_url + 'actions/ytfmt.php'
            }).merge(customAppletParams));
            applet.start();
            _gaq.push(['_trackEvent', 'DownloadBox', 'AppletLoad']);
        } catch (e) {
            this.onError = this.onError.wrap(function(callOriginal, e){
                this.setRetryCallback(undefined);
                callOriginal(e);
            });
            this.onError(e);
        }
    },
    _setLinks: function($super, links) {
        $super(new String(links).evalJSON())
    }
})

var BookmarkClass = Class.create(ContainerTraverse, {

    initialize: function($super, links, options) {
        $super(options);
        this.links = links;
        this.observeClicks();
    },
    observeClicks: function() {
        this.allElems().invoke('observe', 'click', function(e){
            e.stop();
            this.change(this.type($(e.findElement()).up('li')));
        }.bind(this));
    },
    allElems: function() {
        return this.$$('.down-box');
    },
    type: function(elem) {
       return elem.className.match(/bl-(\w+)/)[1] 
    },
    change: function(type) {
        this.allElems().each(function(elem) {
            if (this.type(elem) == type) {
                elem.addClassName('sh-current');
            } else {
                elem.removeClassName('sh-current');
            }
        }, this);
        this.$('input_blog_link').value = this.links[type];
        new Effect.Highlight(this.$('input_blog_link'), {startcolor:'#ffff99', endcolor:'#ffffff', restorecolor:'#ffffff', duration:0.2})
    }
});

function globalFunctionWrapper(name, func) {
    if (typeof func == 'function') {
        window[name] = func;
    }
    return name;
}

var JavaApplet = Class.create({
    initialize: function(params) {
        if (!deployJava.getJREs() || deployJava.getJREs().length==0)
            throw 'errorNoJava';

        var applet_properties = {
            id: 'SavevidApplet2',
            height:'1px',
            width:'1px',
            codetype: 'application/x-java-applet',
            type: 'application/x-java-applet',
            classid: 'clsid:8AD9C840-044E-11D1-B3E9-00805F499D93'//java 1.5
        };
        var attributes = '';
        /*
         DO NOT USE DOM here. IE8 will ignore it
         */
        $H(applet_properties).each(function(item){
            attributes = attributes + ' ' + item.key + '="' + item.value + '"';
        });
        var embed_params = '';
        var object_params = '';
        params.each(function(item){
            embed_params = embed_params + ' ' +item.key+ '="'+ item.value +'"';
            object_params = object_params + '<param name="' +item.key+ '" value="' +item.value+ '" />';
        });
        this.applet = '<' + 'object' + attributes + '>' + object_params;
        this.applet = this.applet + '<comment><embed'+ attributes + embed_params + ' /></comment>';
        this.applet = this.applet + '</object>';
    },
    start: function() {
        $(document.body).insert(this.applet);
    }
});

function flagVideo(id){
	if (typeof(window.flag_id) != "undefined" && window.flag_id == 0) return false;
	window.flag_id = id;
	new Ajax.Updater('flag-box', path_url + 'actions/flagvideo_box.php');
	$('flag-box').addClassName('descr').show()
	return false;
}

function flagVideo2(){
	$('flag-cap-err').update('')
	new Ajax.Request(path_url + 'actions/flagvideo.php?id='+window.flag_id+'&code='+encodeURIComponent($('flag-capcha').value)+'&reason='+$('flag-reason').value+'&r='+Math.random(), {
		method: 'get',
		onSuccess: function (resp){
			if (resp.responseText == 'ok'){
				window.flag_id = 0;
				$('flag-box').update('Thank you for sharing your concerns.')
			}else{
				$('flag-cap-err').update('Wrong capcha')
			}
		}
	})
}

function sendmail(obj) {
	var returner = true;
	var yourname = obj.yourname.value;
	var youremail = obj.youremail.value;
	var comments = obj.comments.value;
	var captcha = obj.captcha.value;
	
	var c_ok = "1px solid #999999";
	var c_er = "1px solid #BA0022";
	
	obj.yourname.style.border = (yourname.length == 0)?c_er:c_ok;
	obj.youremail.style.border = (youremail.length == 0 || !isEmail(youremail))?c_er:c_ok;
	obj.comments.style.border = (comments.length == 0)?c_er:c_ok;
	obj.captcha.style.border = (obj.captcha.value.length == 0)?c_er:c_ok;
	
	if (yourname.length == 0 || youremail.length == 0 || !isEmail(youremail) || comments.length == 0 || obj.captcha.value.length == 0) return false;
	
	$('mail_send').hide()
	
	new Ajax.Request("/actions/sendmail.php", {
		method: 'get',
		parameters:  {
			yourname: yourname,
			youremail: youremail,
			comments: comments,
			captcha: captcha,
			jre: deployJava.getJREs().join(", "),
			r: Math.random()
		},
		onSuccess: function(request) { 
			var respText = request.responseText;
			setTimeout(function(){
				if (respText == 'ok') {
					$('mail_form').hide()
					$('rep_mail_username').update(yourname.escapeHTML())
					$('rep_mail_usermail').update(youremail.escapeHTML())
					$('rep_mail_usertext').update(comments.escapeHTML())
					$('cerror2').style.background = 'url(/images/ok.jpg) no-repeat';
					$('repeat_mail').show()
				} else {
					$('mail_send').style.display = 'block';
					$('cerror').style.background = 'url(/images/error.jpg) no-repeat';
					if (respText == 'captcha')
						obj.captcha.style.border = '1px solid #BA0022';
				}
			}, 2000);
		}
	});
	
	$("cerror").style.background = 'url(/images/loader.gif) no-repeat';
	
}

function carouselAutoScroll(){
	if (typeof(window.carousel_autoscroll) == "undefined") return;
	window.carousel_current += window.carousel_scrollinc;
	if (window.carousel_current >= window.carousel_scrollinc * 5) window.carousel_current = 0;
	for (i in window.carousel_autoscroll){
		if (typeof(window.carousel_autoscroll[i].scrollTo) == "function")
			window.carousel_autoscroll[i].scrollTo(window.carousel_current);
	}
}

function getQueryVariable(variable) {
	return location.search.substring(1).replace(/\?/, '%3F').toQueryParams()[variable]
}

function myCompareStrings(l_s, s_s, del_spaces){
	var dump = l_s;
	if (del_spaces){
		l_s = l_s.replace(/ /g, '');
		s_s = s_s.replace(/ /g, '');
	}
	var all_count = s_s.length;
	var i = 0;
	while ((l_s.charAt(0) == s_s.charAt(0)) && (l_s.substr(0,7) != 'http://')){
		l_s = l_s.substr(1);
		s_s = s_s.substr(1);
		++i;
	}
	while (l_s.charAt(l_s.length - 1) == s_s.charAt(s_s.length - 1)){
		l_s = l_s.substr(0, l_s.length - 1);
		s_s = s_s.substr(0, s_s.length - 1);
		++i;
	}
	if (i > all_count/3) return l_s;
	return dump;
}

function embedYoutubeVideo() {
    if (!this.video || this.video.id_provider != 1 || !redirectTo) {
        throw "Video not found";
    }

    _gaq.push(['_trackEvent', 'WatchPage', 'WatchVideo']);

    //build url
    var url = 'http://' +redirectTo+'/youtube_embed?id=' + encodeURIComponent(this.video.id_video);
    //var url = 'http://' +redirectTo+'/youtube_embed?go_to=' + encodeURIComponent(Video.url);

    $('youtube_embed').update(new Element('iframe', {
        src: url,
        padding:0,
        margin:0,
        scrolling:'no',
        width:'100%',
        height:'370px',
        frameborder:0
    }));
}

function onytplayerStateChange(newState) {
    if (newState == 3 ){
        embedYoutubeVideo();
    }
}

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

document.observe('dom:loaded', function() {
/*
	$$('.image-thumb').each(function(item){
		item.src = item.longDesc;
	});
*/		var url = $('url')

  if (url && (url.value == url.title) )
  	url.value = '';

  if (url && location.hash.startsWith('#url=')) {
    url.value = location.hash.replace(/^#url=/, '');
    runDownload();
  } else if (url) {
    var query_idvideo = getQueryVariable('idvideo') || "";
    var query_url = getQueryVariable('url') || "";
    if( !query_idvideo.toString().strip().empty() || !query_url.toString().strip().empty() )
        runDownload();
  }

  
	['/img/icon-watch.png', '/img/animation.gif', '/img/error.png',
  	'/img/play_sign.png', '/img/pause_sign.png', '/img/av-formats.png'
  	].each(function(it){
  		new Element('img', {src: img_url + it })
  	})
	
	if (url) {
		if (!url.focused){
			urlOnBlur.apply(url)
		} else {
			urlOnFocus.apply(url)
			url.value = myCompareStrings(url.value, url.title, true);
		}
		
		url.observe('focus', urlOnFocus).observe('blur', urlOnBlur)
	}
	
	//add background
    if ($$('.main-top').length) {
        $$('.main-top').first().addClassName('delaybg-top')
        $$('.main-bottom').first().addClassName('delaybg-bot')
        $$('.main-contentg').first().addClassName('delaybg-contentg')
        $$('.main-contentb').first().addClassName('delaybg-contentb')
        $$('body').first().addClassName('delaybg-body')
    }

	var slidebar = $('slidebar')
	if (slidebar) {
		Effect.SlideDown('slidebar')
		document.body.style.padding = slidebar.getStyle('height')
	}
	var f = document.getElementsByTagName('iframe');
	for (var i=0; i<f.length; i++) f[i].src = f[i].src;
});

function closeSlidebar() {
	Effect.SlideUp('slidebar')
	document.body.style.padding = 0
	if ($('do_not_show_slidebar').checked) {
		var curr_date = new Date()
		document.cookie = 'slidebar_show=0; path=/; expires='+new Date(curr_date.getFullYear()+1, curr_date.getMonth(), curr_date.getDate())
	}
}

function centerWindow(element) {
     if($(element) == null) return false;
	 var dimensions = document.viewport.getDimensions();
	 $(element).setStyle({
		top: Math.round((dimensions.height - $(element).getHeight())/2) + 'px',
		left: Math.round((dimensions.width - $(element).getWidth())/2) + 'px'
	 });
}

function urlOnFocus(){
	if ($(this).hasClassName('pure'))
		$(this).removeClassName('pure').value = ''
}

function urlOnBlur() {

	var v = this.value.strip()
	if (v == '' || v == $(this).readAttribute('title'))
		$(this).addClassName('pure').value = $(this).readAttribute('title')
}

function getCookie(c_name) {
	if (document.cookie.length>0) {
		//WARNING: could work incorrectly if one cookie name if suffix of another, for example
		// if cookie='firstVariable=1; Variable=2' then getCookie('Variable')==1
		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 "";
}

// 'Rate video' stars related functions
function starsChange(i, s){
	var items = {1: 'Lame', 2: 'Bleh', 3: 'Alright', 4: 'Good', 5: 'Awesome'}
	if (!$('rate-info'))
		return;
	$('rate-info').update(
		items[i] === undefined 
			? (s.locked?'Thank you for your vote':'Please rate this video')
			: items[i]
	)
}
function setImidiately(i){
	s_rating.locked = true;
	s_rating.setValue(i);
	$('rate-info').update('Thank you for your vote')
}


function trackClickEvent(elem, opts, callback) {
	opts.unshift('_trackEvent')
    _gaq.push(opts)
	callback = callback || Prototype.emptyFunction
	setTimeout(function(){
		callback()
		window.location = elem.href
	}, 2000)
	return false
}


// deployJava.js script embedded here because we can`t change the cached pages code
var deployJava={debug:null,firefoxJavaVersion:null,myInterval:null,preInstallJREList:null,returnPage:null,brand:null,locale:null,installType:null,EAInstallEnabled:false,EarlyAccessURL:null,getJavaURL:"http://java.sun.com/webapps/getjava/BrowserRedirect?host=java.com",appleRedirectPage:"http://www.apple.com/support/downloads/",oldMimeType:"application/npruntime-scriptable-plugin;DeploymentToolkit",mimeType:"application/java-deployment-toolkit",launchButtonPNG:"http://java.sun.com/products/jfc/tsc/articles/swing2d/webstart.png", browserName:null,browserName2:null,getJREs:function(){var a=[];if(deployJava.isPluginInstalled())for(var b=deployJava.getPlugin().jvms,c=0;c<b.getLength();c++)a[c]=b.get(c).version;else{b=deployJava.getBrowser();if(b=="MSIE")if(deployJava.testUsingActiveX("1.7.0"))a[0]="1.7.0";else if(deployJava.testUsingActiveX("1.6.0"))a[0]="1.6.0";else if(deployJava.testUsingActiveX("1.5.0"))a[0]="1.5.0";else if(deployJava.testUsingActiveX("1.4.2"))a[0]="1.4.2";else{if(deployJava.testForMSVM())a[0]="1.1"}else if(b== "Netscape Family"){deployJava.getJPIVersionUsingMimeType();if(deployJava.firefoxJavaVersion!=null)a[0]=deployJava.firefoxJavaVersion;else if(deployJava.testUsingMimeTypes("1.7"))a[0]="1.7.0";else if(deployJava.testUsingMimeTypes("1.6"))a[0]="1.6.0";else if(deployJava.testUsingMimeTypes("1.5"))a[0]="1.5.0";else if(deployJava.testUsingMimeTypes("1.4.2"))a[0]="1.4.2";else if(deployJava.browserName2=="Safari")if(deployJava.testUsingPluginsArray("1.7.0"))a[0]="1.7.0";else if(deployJava.testUsingPluginsArray("1.6"))a[0]= "1.6.0";else if(deployJava.testUsingPluginsArray("1.5"))a[0]="1.5.0";else if(deployJava.testUsingPluginsArray("1.4.2"))a[0]="1.4.2"}}if(deployJava.debug)for(c=0;c<a.length;++c)alert("We claim to have detected Java SE "+a[c]);return a},installJRE:function(a){if(deployJava.isPluginInstalled())if(deployJava.getPlugin().installJRE(a)){deployJava.refresh();if(deployJava.returnPage!=null)document.location=deployJava.returnPage;return true}else return false;else return deployJava.installLatestJRE()},installLatestJRE:function(){if(deployJava.isPluginInstalled())if(deployJava.getPlugin().installLatestJRE()){deployJava.refresh(); if(deployJava.returnPage!=null)document.location=deployJava.returnPage;return true}else return false;else{var a=deployJava.getBrowser(),b=navigator.platform.toLowerCase();if(deployJava.EAInstallEnabled=="true"&&b.indexOf("win")!=-1&&deployJava.EarlyAccessURL!=null){deployJava.preInstallJREList=deployJava.getJREs();if(deployJava.returnPage!=null)deployJava.myInterval=setInterval("deployJava.poll()",3E3);location.href=deployJava.EarlyAccessURL}else if(a=="MSIE")return deployJava.IEInstall();else if(a== "Netscape Family"&&b.indexOf("win32")!=-1)return deployJava.FFInstall();else location.href=deployJava.getJavaURL+(deployJava.returnPage!=null?"&returnPage="+deployJava.returnPage:"")+(deployJava.locale!=null?"&locale="+deployJava.locale:"")+(deployJava.brand!=null?"&brand="+deployJava.brand:"");return false}},runApplet:function(a,b,c){if(c=="undefined"||c==null)c="1.1";var d=c.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$");if(deployJava.returnPage==null)deployJava.returnPage=document.location; if(d!=null)if(deployJava.getBrowser()!="?"&&"Safari"!=deployJava.browserName2)if(deployJava.versionCheck(c+"+"))deployJava.writeAppletTag(a,b);else{if(deployJava.installJRE(c+"+")){deployJava.refresh();location.href=document.location;deployJava.writeAppletTag(a,b)}}else deployJava.writeAppletTag(a,b);else deployJava.debug&&alert("Invalid minimumVersion argument to runApplet():"+c)},writeAppletTag:function(a,b){var c="<applet ",d=false;for(var f in a){c+=" "+f+'="'+a[f]+'"';if(f=="code")d=true}d|| (c+=' code="dummy"');c+=">";document.write(c);if(b!="undefined"&&b!=null){a=false;for(var e in b){if(e=="codebase_lookup")a=true;c='<param name="'+e+'" value="'+b[e]+'">';document.write(c)}a||document.write('<param name="codebase_lookup" value="false">')}document.write("</applet>")},versionCheck:function(a){var b=0,c=a.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?(\\*|\\+)?$");if(c!=null){a=true;for(var d=[],f=1;f<c.length;++f)if(typeof c[f]=="string"&&c[f]!=""){d[b]=c[f];b++}if(d[d.length- 1]=="+"){a=false;d.length--}else d[d.length-1]=="*"&&d.length--;b=deployJava.getJREs();for(f=0;f<b.length;++f)if(deployJava.compareVersionToPattern(b[f],d,a))return true}else alert("Invalid versionPattern passed to versionCheck: "+a);return false},isWebStartInstalled:function(a){if(deployJava.getBrowser()=="?"||"Safari"==deployJava.browserName2)return true;if(a=="undefined"||a==null)a="1.4.2";var b=false;if(a.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$")!=null)b=deployJava.versionCheck(a+ "+");else{deployJava.debug&&alert("Invalid minimumVersion argument to isWebStartInstalled(): "+a);b=deployJava.versionCheck("1.4.2+")}return b},getJPIVersionUsingMimeType:function(){for(var a=0;a<navigator.mimeTypes.length;++a){var b=navigator.mimeTypes[a].type.match(/^application\/x-java-applet;jpi-version=(.*)$/);if(b!=null){deployJava.firefoxJavaVersion=b[1];break}}},launchWebStartApplication:function(a){var b=navigator.userAgent.toLowerCase();deployJava.getJPIVersionUsingMimeType();if(b.indexOf("windows", 0)!=-1){if(deployJava.isWebStartInstalled("1.6.0_18")==false)if(deployJava.isPluginInstalled()){if(deployJava.installLatestJRE()==false){alert("Java install failed: cannot use launchWebStartApplication function");return}}else{alert("Please visit java.com to install Java and try again after");return}}else{if(deployJava.firefoxJavaVersion==null){alert("Please visit java.com to install Java and try again after");return}if(deployJava.firefoxJavaVersion<"1.6.0_18"){alert("Please visit java.com to install Java and try again after"); return}}b=null;if(document.documentURI)b=document.documentURI;if(b==null)b=document.URL;var c=deployJava.getBrowser();if(c=="MSIE")document.write('<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="0" height="0"><PARAM name="launchjnlp" value="'+a+'"><PARAM name="docbase" value="'+b+'"></object>');else c=="Netscape Family"&&document.write('<embed type="application/x-java-applet;jpi-version='+deployJava.firefoxJavaVersion+'" width="0" height="0" launchjnlp="'+a+'"docbase="'+b+'" />'); document.location=b},createWebStartLaunchButtonEx:function(a){if(deployJava.returnPage==null)deployJava.returnPage=a;document.write('<a href="'+("javascript:deployJava.launchWebStartApplication('"+a+"');")+'" onMouseOver="window.status=\'\'; return true;"><img src="'+deployJava.launchButtonPNG+'" border="0" /></a>')},createWebStartLaunchButton:function(a,b){if(deployJava.returnPage==null)deployJava.returnPage=a;document.write('<a href="'+("javascript:if (!deployJava.isWebStartInstalled(&quot;"+b+ "&quot;)) {if (deployJava.installLatestJRE()) {if (deployJava.launch(&quot;"+a+"&quot;)) {}}} else {if (deployJava.launch(&quot;"+a+"&quot;)) {}}")+'" onMouseOver="window.status=\'\'; return true;"><img src="'+deployJava.launchButtonPNG+'" border="0" /></a>')},launch:function(a){if(deployJava.isPluginInstalled())return deployJava.getPlugin().launch(a);else{document.location=a;return true}},isPluginInstalled:function(){var a=deployJava.getPlugin();return a&&a.jvms?true:false},isAutoUpdateEnabled:function(){if(deployJava.isPluginInstalled())return deployJava.getPlugin().isAutoUpdateEnabled(); return false},setAutoUpdateEnabled:function(){if(deployJava.isPluginInstalled())return deployJava.getPlugin().setAutoUpdateEnabled();return false},setInstallerType:function(a){deployJava.installType=a;if(deployJava.isPluginInstalled())return deployJava.getPlugin().setInstallerType(a);return false},setAdditionalPackages:function(a){if(deployJava.isPluginInstalled())return deployJava.getPlugin().setAdditionalPackages(a);return false},setEarlyAccess:function(a){deployJava.EAInstallEnabled=a},isPlugin2:function(){if(deployJava.isPluginInstalled())if(deployJava.versionCheck("1.6.0_10+"))try{return deployJava.getPlugin().isPlugin2()}catch(a){}return false}, allowPlugin:function(){deployJava.getBrowser();return"Chrome"!=deployJava.browserName2&&"Safari"!=deployJava.browserName2&&"Opera"!=deployJava.browserName2},getPlugin:function(){deployJava.refresh();var a=null;if(deployJava.allowPlugin())a=document.getElementById("deployJavaPlugin");return a},compareVersionToPattern:function(a,b,c){var d=a.match("^(\\d+)(?:\\.(\\d+)(?:\\.(\\d+)(?:_(\\d+))?)?)?$");if(d!=null){var f=0;a=[];for(var e=1;e<d.length;++e)if(typeof d[e]=="string"&&d[e]!=""){a[f]=d[e];f++}d= Math.min(a.length,b.length);if(c)for(e=0;e<d;++e){if(a[e]!=b[e])return false}else for(e=0;e<d;++e)if(a[e]<b[e])return false;else if(a[e]>b[e])return true;return true}else return false},getBrowser:function(){if(deployJava.browserName==null){var a=navigator.userAgent.toLowerCase();deployJava.debug&&alert("userAgent -> "+a);if(a.indexOf("msie")!=-1){deployJava.browserName="MSIE";deployJava.browserName2="MSIE"}else if(a.indexOf("firefox")!=-1){deployJava.browserName="Netscape Family";deployJava.browserName2= "Firefox"}else if(a.indexOf("chrome")!=-1){deployJava.browserName="Netscape Family";deployJava.browserName2="Chrome"}else if(a.indexOf("safari")!=-1){deployJava.browserName="Netscape Family";deployJava.browserName2="Safari"}else if(a.indexOf("mozilla")!=-1){deployJava.browserName="Netscape Family";deployJava.browserName2="Other"}else if(a.indexOf("opera")!=-1){deployJava.browserName="Netscape Family";deployJava.browserName2="Opera"}else{deployJava.browserName="?";deployJava.browserName2="unknown"}deployJava.debug&& alert("Detected browser name:"+deployJava.browserName+", "+deployJava.browserName2)}return deployJava.browserName},testUsingActiveX:function(a){a="JavaWebStart.isInstalled."+a+".0";if(!ActiveXObject){deployJava.debug&&alert("Browser claims to be IE, but no ActiveXObject object?");return false}try{return new ActiveXObject(a)!=null}catch(b){return false}},testForMSVM:function(){if(typeof oClientCaps!="undefined"){var a=oClientCaps.getComponentVersion("{08B0E5C0-4FCB-11CF-AAA5-00401C608500}","ComponentID"); return a==""||a=="5,0,5000,0"?false:true}else return false},testUsingMimeTypes:function(a){if(!navigator.mimeTypes){deployJava.debug&&alert("Browser claims to be Netscape family, but no mimeTypes[] array?");return false}for(var b=0;b<navigator.mimeTypes.length;++b){s=navigator.mimeTypes[b].type;var c=s.match(/^application\/x-java-applet\x3Bversion=(1\.8|1\.7|1\.6|1\.5|1\.4\.2)$/);if(c!=null)if(deployJava.compareVersions(c[1],a))return true}return false},testUsingPluginsArray:function(a){if(!navigator.plugins|| !navigator.plugins.length)return false;for(var b=navigator.platform.toLowerCase(),c=0;c<navigator.plugins.length;++c){s=navigator.plugins[c].description;if(s.search(/^Java Switchable Plug-in (Cocoa)/)!=-1){if(deployJava.compareVersions("1.5.0",a))return true}else if(s.search(/^Java/)!=-1)if(b.indexOf("win")!=-1)if(deployJava.compareVersions("1.5.0",a)||deployJava.compareVersions("1.6.0",a))return true}if(deployJava.compareVersions("1.5.0",a))return true;return false},IEInstall:function(){location.href= deployJava.getJavaURL+(deployJava.returnPage!=null?"&returnPage="+deployJava.returnPage:"")+(deployJava.locale!=null?"&locale="+deployJava.locale:"")+(deployJava.brand!=null?"&brand="+deployJava.brand:"")+(deployJava.installType!=null?"&type="+deployJava.installType:"");return false},done:function(){},FFInstall:function(){location.href=deployJava.getJavaURL+(deployJava.returnPage!=null?"&returnPage="+deployJava.returnPage:"")+(deployJava.locale!=null?"&locale="+deployJava.locale:"")+(deployJava.brand!= null?"&brand="+deployJava.brand:"")+(deployJava.installType!=null?"&type="+deployJava.installType:"");return false},compareVersions:function(a,b){a=a.split(".");b=b.split(".");for(var c=0;c<a.length;++c)a[c]=Number(a[c]);for(c=0;c<b.length;++c)b[c]=Number(b[c]);if(a.length==2)a[2]=0;if(a[0]>b[0])return true;if(a[0]<b[0])return false;if(a[1]>b[1])return true;if(a[1]<b[1])return false;if(a[2]>b[2])return true;if(a[2]<b[2])return false;return true},enableAlerts:function(){deployJava.browserName=null; deployJava.debug=true},poll:function(){deployJava.refresh();var a=deployJava.getJREs();if(deployJava.preInstallJREList.length==0&&a.length!=0){clearInterval(deployJava.myInterval);if(deployJava.returnPage!=null)location.href=deployJava.returnPage}if(deployJava.preInstallJREList.length!=0&&a.length!=0&&deployJava.preInstallJREList[0]!=a[0]){clearInterval(deployJava.myInterval);if(deployJava.returnPage!=null)location.href=deployJava.returnPage}},writePluginTag:function(){var a=deployJava.getBrowser(); if(a=="MSIE")document.write('<object classid="clsid:CAFEEFAC-DEC7-0000-0000-ABCDEFFEDCBA" id="deployJavaPlugin" width="0" height="0"></object>');else a=="Netscape Family"&&deployJava.allowPlugin()&&deployJava.writeEmbedTag()},refresh:function(){navigator.plugins.refresh(false);deployJava.getBrowser()=="Netscape Family"&&deployJava.allowPlugin()&&document.getElementById("deployJavaPlugin")==null&&deployJava.writeEmbedTag()},writeEmbedTag:function(){var a=false;if(navigator.mimeTypes!=null){for(var b= 0;b<navigator.mimeTypes.length;b++)if(navigator.mimeTypes[b].type==deployJava.mimeType)if(navigator.mimeTypes[b].enabledPlugin){document.write('<embed id="deployJavaPlugin" type="'+deployJava.mimeType+'" hidden="true" />');a=true}if(!a)for(b=0;b<navigator.mimeTypes.length;b++)navigator.mimeTypes[b].type==deployJava.oldMimeType&&navigator.mimeTypes[b].enabledPlugin&&document.write('<embed id="deployJavaPlugin" type="'+deployJava.oldMimeType+'" hidden="true" />')}},do_initialize:function(){deployJava.writePluginTag(); if(deployJava.locale==null){var a=null;if(a==null)try{a=navigator.userLanguage}catch(b){}if(a==null)try{a=navigator.systemLanguage}catch(c){}if(a==null)try{a=navigator.language}catch(d){}if(a!=null){a.replace("-","_");deployJava.locale=a}}}};deployJava.do_initialize();

