//global variables definition
var currentBlogId=null;
var currentCommentId=null;
var currentSubCommentId=null;
var currentSessionId=null;
var currentBloggerId=null;
var currentWidgetType="BANDS_VIEWS";
var currentBandStringId=null;
var currentBandNameForWidget=null;
var currentUsername=null;

var flashReadyToAcceptJSCalls=false;
function writeFlash(randomParam, flashPath) {
    var innerWhere = document.getElementById('widget');
    var url = flashPath + "/common/base_swf/index.swf?random=" + randomParam+'&widget_type=BANDS_VIEWS&band_event_name='+currentBandNameForWidget;
//    var url = "/common/swf/index.swf?random=" + randomParam;

    var settingsLocation = location.protocol + '//' + location.host + ( location.port ? ':' + location.port : '') + '/actions/getWidgetSettings.action';
    
    var flashVars = 'on_site=1&random='+randomParam +
    	'&xml_settings_url=' + settingsLocation;

    var whatWrite = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' +
                    'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"';

    whatWrite += 'id="game"  height="385" width="450">';


    whatWrite = whatWrite + '<param name="allowScriptAccess" value="always"/>' +
                '<param name="allowNetworking" value="all"/>' +
        //                '<param name="allowFullScreen" value="true"/>' +
                '<param name="movie" value="' + url + '"/>' +
                '<param name="quality" value="best"/>' +
                '<PARAM NAME="MAYSCRIPT" VALUE="true">' +
                '<param name="wmode" value="transparent"/>' +
                '<param name="play" value="true">' +
                '<param name="scale" value="noscale"/>' +
                '<param name="FlashVars"' +
                'value="' + flashVars +
                '"/>' +
                '<embed id="gameEmbed" src="' + url +
                '" quality="best" scale="noscale"' +
                '       wmode="transparent"' +
                'name="game" align="left" MAYSCRIPT="true" swLiveConnect="true"' +
                'allowNetworking="all" allowFullScreen="true" AllowScriptAccess="always" type="application/x-shockwave-flash "' +
                'FlashVars="' + flashVars + '"' +
                'pluginspage="http://www.macromedia.com/go/getflashplayer"';
    whatWrite += ' height="385" width="450"';

    whatWrite = whatWrite + '/>' +
                '</object> ';
    innerWhere.innerHTML = whatWrite;

}
function initFlashFromJavaScript() {
    var flash_params = "";
    flash_params += 'blog_id=' + currentBlogId;
    flash_params += ',blogger_id=' + currentBloggerId;
    flash_params += ',comment_id=' + currentCommentId;
    flash_params += ',session_id=' + currentSessionId;
    flash_params += ',widget_type=' + currentWidgetType;
    flash_params += ',band_event_name=' + currentBandNameForWidget;
    flash_params+= ',sub_comment_id=' + currentSubCommentId;
    return flash_params;
}

function scroller(content){
	//variables
	var horisontal;
	this.horisontal = horisontal;
	var contentdiv = content;
	this.contentdiv = contentdiv;
	var framediv;
	this.framediv = framediv;
	var url;
	this.url = url;
	var comments = [];
	this.comments = comments;
	var loadingFlag = false;
	this.loadingFlag = loadingFlag;
	var offset = 0;
	this.offset = offset;
	var commentsObj;
	this.commentsObj = commentsObj;
	var total = 0;
	this.total = total;
	var commentsArray
	this.commentsArray = commentsArray;
	var page = 0;
	this.page = page;
	var itemsPerPage;
	this.itemsPerPage = itemsPerPage;
	var loadingSplash;
	this.loadingSplash = loadingSplash;
	var dataPortionLoadedEvent = new ScrollerCustomEvent("dataPortionLoadedEvent");
	this.dataPortionLoadedEvent = dataPortionLoadedEvent;
	var prefix;
	this.prefix = prefix;
	var pageClass
	this.pageClass = pageClass
	var ajaxReq;
	this.ajaxReq = ajaxReq;
	
	
	var params;
    this.params=params;
    //functions
	this.loadJson = loadJson;
	this.scroll = scroll;
	this.ScrollerCustomEvent = ScrollerCustomEvent;
	this.showSplash = showSplash;
	this.hideSplash = hideSplash;
	this.buildChild = buildChild;
	this.doScroll = doScroll;
	this.appendPortionDiv = appendPortionDiv;
	this.restoreState = restoreState;
	
	
	//impl
	function loadJson(offset){
	
    	if(this.loadingFlag){
    		return;
    	}
    	
    	var err = function (o){}
    	this.loadingFlag = true;
	    var u = this.url;
	    var postData = 'offset=' + offset;
	    
	    if(this.params){
	    	for(key in this.params){
	    		postData = postData + "&" + key + "=" + this.params[key];
	    	}
	    }
	    ajaxReq = YAHOO.util.Connect.asyncRequest(
	    	'POST',
	    	u,
	    	{success:processResult, failure:err, argument:[this]},
	    	postData
	    );
	    
	}
	
	function processResult(o){
		o.argument[0].loadingFlag = false;
		o.argument[0].hideSplash();
		
		var obj = YAHOO.lang.JSON.parse(o.responseText);
		if(o.argument[0].commentsObj){
   			obj = obj[o.argument[0].commentsObj]
   		}
   		o.argument[0].total=obj.total;
   		var arrName = o.argument[0].commentsArray;
		var ofst = o.argument[0].comments.length;
   		for (var i=0; i<obj[arrName].length; i++){
   			o.argument[0].comments[ofst + i] = obj[arrName][i];
   		}
   		o.argument[0].dataPortionLoadedEvent.event.fire();
	}
	
	function scroll(dir){
		if (((this.page + dir) < 0) || ((this.page + dir) * this.itemsPerPage >= this.total)){
			return;
		}
		if(((this.page + dir) * this.itemsPerPage >=  this.comments.length) &&
				((this.page + dir) * this.itemsPerPage < this.total) &&
				this.loadingFlag){
			this.showSplash();
			return;
		}
		
		if (YAHOO.util.Dom.get(this.prefix+(this.page - 2 * dir))){
			YAHOO.util.Dom.get(this.prefix+(this.page - 2 * dir)).innerHTML='';
		}
		if (!YAHOO.util.Dom.get(this.prefix+(this.page + dir))){
			appendPortionDiv(this.page + dir, this);
		}
		if(YAHOO.util.Dom.getChildren(this.prefix+(this.page + dir)).length == 0){
			this.buildChild(YAHOO.util.Dom.get(this.prefix+(this.page + dir)), dir);
		}
		
		this.doScroll(dir);
		this.page = dir + this.page;
		
		var r = Math.min((this.page*this.itemsPerPage + this.itemsPerPage), this.total);
  		
		if(((this.page * this.itemsPerPage) > (this.comments.length - this.itemsPerPage * 10))
				&& this.comments.length < this.total
			){
			this.loadJson(this.comments.length);
		}
		if((this.page+1) * this.itemsPerPage >= this.total){
			YAHOO.util.Dom.addClass(this.downId, "inactive");
			YAHOO.util.Dom.removeClass(this.downId, "clickable");
		} else {
			YAHOO.util.Dom.removeClass(this.downId, "inactive");
			YAHOO.util.Dom.addClass(this.downId, "clickable");
		}
		
		if(this.page == 0){
			YAHOO.util.Dom.addClass(this.upId, "inactive");
			YAHOO.util.Dom.removeClass(this.upId, "clickable");
		} else {
			YAHOO.util.Dom.removeClass(this.upId, "inactive");
			YAHOO.util.Dom.addClass(this.upId, "clickable");
		}
		if (this.total == 0){
			YAHOO.util.Dom.addClass(this.upId, "inactive");
			YAHOO.util.Dom.removeClass(this.upId, "clickable");
			YAHOO.util.Dom.addClass(this.downId, "inactive");
			YAHOO.util.Dom.removeClass(this.downId, "clickable");
		}
	}
	
	function appendPortionDiv(numb, scr){
		var d = document.createElement("div");
       	d.id = scr.prefix + (numb);
       	YAHOO.util.Dom.addClass(d, scr.pageClass);
       	YAHOO.util.Dom.get(scr.contentdiv).appendChild(d);
       	
       	var reg = YAHOO.util.Dom.getRegion  ( scr.contentdiv );
       	var reg1 = YAHOO.util.Dom.getRegion  ( d );
       	if(scr.horisontal){
       		var w = (reg.right - reg.left) + (reg1.right - reg1.left);
       		YAHOO.util.Dom.setStyle  ( scr.contentdiv , "width" , w + "px" );
       	} else {
       		var h = (reg.bottom - reg.top) + (reg1.bottom - reg1.top);
       		YAHOO.util.Dom.setStyle  ( scr.contentdiv , "height" , h + "px" );
       	}
	}
	
	function doScroll(dir){
		var reg = YAHOO.util.Dom.getRegion  ( this.framediv );
   		var h = reg.bottom - reg.top;
   		var w = reg.right - reg.left;
    	var attributes = this.horisontal ?
    		{scroll: { to: [(this.page * w + dir * w), 0]}}:
    		{scroll: { to: [0, (this.page * h + dir * h)]}};
	    an = new YAHOO.util.Scroll(this.framediv, attributes);
	    an.duration = 0.5;
	    an.animate();	
    }
    
    function restoreState(){
    	if(ajaxReq && YAHOO.util.Connect.isCallInProgress(ajaxReq)){
    		YAHOO.util.Connect.abort(ajaxReq,null,false);
    		this.loadingFlag=false;
    	}
    	var cnt = YAHOO.util.Dom.get(this.contentdiv);
    	var childs = YAHOO.util.Dom.getChildren(cnt);
    	for (var i = childs.length -1; i>=0; i--){
    		YAHOO.util.Dom.get(this.contentdiv).removeChild(childs[i]);
    	}
    	YAHOO.util.Dom.setStyle  ( this.contentdiv , "width" , 0 );
    	for (var i=0; i<= this.page; i++){
    		this.appendPortionDiv(i, this);
    	}
    	if (this.comments.length > 0){
    		this.buildChild(YAHOO.util.Dom.get(this.prefix+this.page), 0);
    		var reg = YAHOO.util.Dom.getRegion  ( this.framediv );
	   		var h = reg.bottom - reg.top;
	   		var w = reg.right - reg.left;
    		var attributes = this.horisontal ?
	    		{scroll: { to: [(this.page * w), 0]}}:
	    		{scroll: { to: [0, (this.page * h)]}};
		    an = new YAHOO.util.Scroll(this.framediv, attributes);
		    an.duration = 0;
		    an.animate();
    	}
    }
    
	
	function showSplash(){
		var xy = YAHOO.util.Dom.getXY(this.contentdiv);
		var size=YAHOO.util.Dom.getRegion(this.contentdiv);
		YAHOO.util.Dom.setStyle(this.loadingSplash, 'width',(size.right - size.left +  50) + 'px');
		YAHOO.util.Dom.setStyle(this.loadingSplash, 'height',(size.bottom - size.top) + 'px');
    	YAHOO.util.Dom.removeClass(this.loadingSplash, 'invisible_block');
    	YAHOO.util.Dom.setStyle(this.loadingSplash, 'left', xy[0] + 'px');
    	YAHOO.util.Dom.setStyle(this.loadingSplash, 'top', xy[1] + 'px');
	}
	
	function hideSplash(){
		YAHOO.util.Dom.addClass(this.loadingSplash, 'invisible_block');
	}
	
	function ScrollerCustomEvent(name) {
	    this.name = name;
	    this.event = new YAHOO.util.CustomEvent(name, this);
	}
	
	function buildChild(node, dir){
		offset = (this.page + dir) * this.itemsPerPage;
		for (i=0; i<this.itemsPerPage; i++){
			var n = offset+i;
			if (n >= this.comments.length){
				break;
			}
			var dd = document.createElement("div");
			YAHOO.util.Dom.setStyle  (dd, "float" ,"left" );//IE HACK
			
			var d = document.createElement("div");
			YAHOO.util.Dom.addClass(d, "thumb");
			YAHOO.util.Dom.setStyle  (d, "float" ,"none" );//IE HACK
			var h = "javascript:clickOnComment('" +this.comments[n].commentId + "', '"+this.comments[n].parentCommentId +"')";
			var a = document.createElement("a");
			a.href=h;
			var img = document.createElement("img");
			img.src = this.comments[n].url + ".jpg" + "?" + this.comments[n].version;
			var date = new Date(this.comments[n].createdDate);
			
			a.appendChild(img);
			d.appendChild(a);
			var di = document.createElement("div");
			a = document.createElement("a");
			a.href=h;
			var day = new String (date.getDate());
			if (day.length ==1) {
				day = "0" + day;
			}
			var month = new String (date.getMonth()+1);
			if (month.length ==1) {
				month = "0" + month;
			} 
			var year = new String (date.getYear());
			if (year.length > 2) {
				year = year.substring(year.length-2);
			}
			a.innerHTML=month+"/" +day+ "/"+ year;//this.comments[n].userName;
			di.appendChild(a);
			d.appendChild(di);
			dd.appendChild(d);
			node.appendChild(dd);
		}
	}
}
function commonLogout(){
    currentBloggerId = null;
    currentSessionId = null;
    wrappedCallToFlash("JSLogout");
}
function processLogout(){
    var handleSuccess = function(o) {
        if (o.responseText !== undefined) {
            document.getElementById('authorization_info').innerHTML = o.responseText;
            commonLogout();
        }
    };
    var handleFailure = function(o) {if (o.responseText !== undefined) {}};
    var callback =    {success:handleSuccess,failure:handleFailure};
    var cObj = YAHOO.util.Connect.asyncRequest('GET', "/common-actions/processLogout.action", callback);
}
function processRockthebellsLogout(){
    var handleSuccess = function(o) {
        if (o.responseText !== undefined) {
            commonLogout();
        }
    };
    var handleFailure = function(o) {if (o.responseText !== undefined) {}};
    var callback =    {success:handleSuccess,failure:handleFailure};
    var cObj = YAHOO.util.Connect.asyncRequest('GET', "/common-actions/processLogout.action", callback);
}
function processRapdreamsLogout(){
	var handleSuccess = function(o) {
        if (o.responseText !== undefined) {
            commonLogout();
            window.location="/";
        }
    };
    var handleFailure = function(o) {if (o.responseText !== undefined) {}};
    var callback =    {success:handleSuccess,failure:handleFailure};
    var cObj = YAHOO.util.Connect.asyncRequest('GET', "/common-actions/processLogout.action", callback);
}
function logoutWithRedirect(where){
    var handleSuccess = function(o) {
        if (o.responseText !== undefined) {
            jumpToURL(where);
        }
    };
    var handleFailure = function(o) {if (o.responseText !== undefined) {}};
    var callback =    {success:handleSuccess,failure:handleFailure};
    var cObj = YAHOO.util.Connect.asyncRequest('GET', "/common-actions/processLogout.action", callback);
}
function jumpToURL(url) {
    window.location = url;
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}
function getBlipbackAS3WidgetInterface() {
    return thisMovie("game");
}
function callToASJumpToComment(commentId) {
//    getBlipbackAS3WidgetInterface().JSJumpToComment(commentId);
    wrappedCallToFlash("JSJumpToComment",commentId);
}
function callToASJumpToSubComment(commentId,subCommentId) {
//    alert("callToASJumpToSubComment:"+commentId+"-"+subCommentId);
//    getBlipbackAS3WidgetInterface().JSJumpToSubComment(commentId,subCommentId);
    wrappedCallToFlash("JSJumpToSubComment",commentId, subCommentId);
}
function wrappedCallToFlash(functionName, parameter1,parameter2) {
    var blipbackInterface = new getBlipbackAS3WidgetInterface();
    if(flashReadyToAcceptJSCalls)
        if(parameter2){
            blipbackInterface[functionName](parameter1,parameter2);
        }
        else if(parameter1)
            blipbackInterface[functionName](parameter1);
        else
            blipbackInterface[functionName]();
}
String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

function FlashLogin(sessionId) {
    var sess = document.getElementById('sessionIdHid');
    sess.value = sessionId;
    loginRequest(true);
}
function FlashLogout() {
    logoutEvent.fire();
}
function FlashJumpToSettings(){
    jumpToURL("/viewUserInfo?showEmailSettings=true");
}
function FlashLoaded(){
    flashReadyToAcceptJSCalls=true;
}
function loginRequest(fromFlash) {
    var handleSuccess = function(o) {
        if (o.responseText !== undefined) {
            var myObject = YAHOO.lang.JSON.parse(o.responseText);
            currentBloggerId=myObject.bloggerId;
            currentSessionId=myObject.sessionId;
            currentUsername=myObject.username;
            if(currentSessionId!=null){
                wrappedCallToFlash("reinitializeFromJavaScript");
                var bandVendors = currentBandVendors.split(/,/);
                for (i = 0; i < bandVendors.length; i++) {
                    if(bandVendors[i]==currentBloggerId){
                        loginEvent.fire("vendor");
                        return;
                    }
                }
                loginEvent.fire();
            } else {
            	document.getElementById("invalid_login").innerHTML="Incorrect username or password";
            }
        }
    };
    var handleFailure = function(o) {};
    var callback =    {success:handleSuccess,failure:handleFailure};
    if(fromFlash!=null&&fromFlash==true){
        var logonForm = document.getElementById('logonForm');
        logonForm.userName.value= null;
        logonForm.password.value= null;
    }else{
        var sess = document.getElementById('sessionIdHid');
        sess.value = "";
    }
    var formObject = document.getElementById('logonForm');
    YAHOO.util.Connect.setForm(formObject);
    var cObj = YAHOO.util.Connect.asyncRequest('POST', "/common-actions/ajaxLogin.action", callback);
    return false;
}

function baseLoginLogout(){
	YAHOO.util.Event.addListener("logout_button", "click", function () {
        logoutEvent.fire();
    });
    logoutEvent.subscribe(function (){
        processLogout();
    });
    YAHOO.util.Event.addListener("logonForm", "submit", function () {
        return false;
    });

    loginEvent.subscribe(function () {
        var handleSuccess = function(o) {
            if (o.responseText !== undefined) {
                document.getElementById('authorization_info').innerHTML = o.responseText;
                YAHOO.util.Event.addListener("logout_button", "click", function () {
                    logoutEvent.fire();
                });
            }
        };
        var handleFailure = function(o) {if (o.responseText !== undefined) {}};
        var callback ={success:handleSuccess,failure:handleFailure};
        var postData = 'bandName=' + currentBandStringId;
        YAHOO.util.Connect.asyncRequest('POST', "/common-actions/showAuthorizationInfo.action", callback,postData);
    });	
}
function rockTheBellsLoginLogout(){
    YAHOO.util.Event.addListener("logonForm", "submit", function () {
        return false;
    });
    logoutEvent.subscribe(function (){
        processRockthebellsLogout()();
    });
}

YAHOO.util.Connect.syncRequest = function(method, uri, callback, postData){
	var o = this.getConnectionObject();

	if(!o){
		return null;
	} else{
		if(this._isFormSubmit){
			if(this._isFileUpload){
				this.uploadFile(o.tId, callback, uri, postData);
				this.releaseObject(o);
				return;
			}
			//If the specified HTTP method is GET, setForm() will return an
			//encoded string that is concatenated to the uri to
			//create a querystring.
			if(method == 'GET'){
				if(this._sFormData.length != 0){
					// If the URI already contains a querystring, append an ampersand
					// and then concatenate _sFormData to the URI.
					uri += ((uri.indexOf('?') == -1)?'?':'&') + this._sFormData;
				} else {
					uri += "?" + this._sFormData;
				}
			} else if(method == 'POST'){
				//If POST data exist in addition to the HTML form data,
				//it will be concatenated to the form data.
				postData = postData?this._sFormData + "&" + postData:this._sFormData;
			}
		}
		// THIS IS THE ONLY DIFFERENT LINE FROM THE STANDARD asyncRequest()
		o.conn.open(method, uri, false);
		if(this._isFormSubmit || (postData && this._use_default_post_header)){
			this.initHeader('Content-Type', this._default_post_header);
			if(this._isFormSubmit){
				this.resetFormState();
			}
		}
		
		if(this._has_http_headers){
			this.setHeader(o);
		}

		this.handleReadyState(o, callback);
o.conn.send(postData || null);

return o;
}
};

function heartBeat(){
    
    var succ = function(o){}
    var err = function(o){}
    ajaxReq = YAHOO.util.Connect.asyncRequest(
        'GET',
        '/common-actions/heartbeat.action',
        {success:succ, failure:err, argument:[this]}
    );
    setTimeout(heartBeat, 5 * 60 * 1000);
}

YAHOO.util.Event.onDOMReady(new function(){setTimeout(heartBeat, 5 * 60 * 1000)});
