$.cbz = function(){}
$.cbz.commons = function(){}
$.cbz.ui = function(){}

$.cbz.log=function(obj){
	if (typeof(console) == 'object') {
		console.log(obj);
	}
};

$.cbz.error = function(Exception){
    $.cbz.log(Exception);    
};

$.cbz.commons.sanitize = function(str){
   return str.replace(/[ ,]/gi, "-").replace(/[*]/gi, "");
};

$.cbz.commons.sortByMatchIndex = function(data) {
	sortedArray = [];
	for(var key in data) {
		sortedArray[data[key].matchIndex] = data[key];
	}
	if($.browser.msie) {
		data = sortedArray.reverse();
	}
	else {
		data = sortedArray;
	}
	return data;
}

$.cbz.commonPopup = function(url,name,props){
	newwindow=window.open(url,"",'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=0,'+props+',left=30,top=30');
	if (window.focus) {
		newwindow.focus()
	}
	return false;
}
$.cbz.commons.getRandom = function(){
    return new Date().getTime()
}

$.cbz.commons.getMatchFolder = function (data, client) {
	return data.matchId + ", '/includes/" + client + "/livecricketscore/" + data.seriesFolderYear + "/" + data.matchFolder;
}
$.cbz.ui.tabs = function(container){
	$.cbz.ui.tabs.layout(container,"tabs")
}
$.cbz.ui.tabs.small = function(container){
    $.cbz.ui.tabs.layout(container,"tabs")
}
$.cbz.ui.tabs.layout = function(container,tabclass){
    var tabContainers = $('div.' + container + ' > div');
    tabContainers.hide().filter(':first').show();
    $('div.' + container + ' ul.' + tabclass + ' a').click(function () {
        tabContainers.hide();
        tabContainers.filter(this.hash).show();
        $('div.' + container + ' ul.' + tabclass + ' a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    }).filter(':first').click();
}
$.cbz.ui.tabs.setActiveTab = function(container,tabclass,activeTabName){
	if(activeTabName != null){
		$("." + tabclass).hide();
		$("div." + container + " ul li").each(function(){
			var activeTab = $(this).find("a").attr("href")
			$(this).removeClass("active");
			if(activeTab == activeTabName){
				$(this).addClass("active").show();
			}
		})
	}
	else{
		$("." + tabclass).hide();
		$("div." + container + " ul li:first").addClass("active").show();
	}
	
}
$.cbz.ui.slider  = function(menu_class,image_class,slider_window){
	$(menu_class).show();
	$(menu_class + " a:first").addClass("active");
		
	var imageWidth = $(slider_window).width();
	var slideSum = $(image_class + " span").size();
	var imageReelWidth = imageWidth * slideSum;
	//Adjust the image reel to its new size
	$(image_class).css({'width' : imageReelWidth});
	
	//Paging + Slider Function
	rotate = function(){	
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
		$(menu_class + " a").removeClass('active'); //Remove all active class
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
		
		//Slider Animation
		$(image_class).animate({ 
			left: -image_reelPosition
		}, 500 );
		
	}; 
	
	//Rotation + Timing Event
	rotateSwitch = function(){		
		play = setInterval(function(){ //Set timer - this will repeat itself every 3 seconds
			$active = $(menu_class + ' a.active').next();
			if ( $active.length === 0) { //If paging reaches the end...
				$active = $( menu_class + ' a:first'); //go back to first
			}
			rotate(); //Trigger the paging and slider function
		}, 7000); //Timer speed in milliseconds (3 seconds)
	};
	
	rotateSwitch(); //Run function on launch

	//On Hover
	$(image_class + " span").hover(function() {
		clearInterval(play); //Stop the rotation
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	//On Click
	$(menu_class + " a").click(function() {	
		$active = $(this); //Activate the clicked paging
		//Reset Timer
		clearInterval(play); //Stop the rotation
		rotate(); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});	
	
}
$.cbz.ui.cworldtabs = function(container,tabclass){
    $("." + tabclass).hide();
	$("div." + container + " ul li:first").addClass("active").show();
	$("." + tabclass + ":first").show();
	
	$("div." + container + " > ul > li").click(function () {
		$("div." + container + " ul > li").each(function(){
			if($(this).parent().parent().hasClass(container)){
				$(this).removeClass("active");
			}
		}) //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$("." + tabclass).hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the href
		if(activeTab.indexOf("http://") >= 0 ){
			tabvalue = activeTab.split("#");
			if(tabvalue[1] != null){
				activeTab = "#" + tabvalue[1];
			}
		}
		$(activeTab).fadeIn(100); //Fade in the active ID content
		return false;
	})
}

$.cbz.ui.toggler = function(container,cntContainer){
    postfix = "_toggleContent"
        if(cntContainer != null )
         postfix  = cntContainer 
    contentContainer = $("."  + container).attr("id") + postfix;
    $("#"+contentContainer).hide()
    $("."  + container).click(function(){
        $(this).toggleClass("expand");
        $(this).toggleClass("collapse");
        thisId =  "#" + $(this).attr('id') + ';';
        containerId = "#" + $(this).attr('id') + postfix;
        $(containerId).slideToggle();	
    });
}

$.cbz.ui.reversetoggler = function(container,cntContainer){
    postfix = "_toggleContent"
        if(cntContainer != null )
         postfix  = cntContainer 
    contentContainer = $("."  + container).attr("id") + postfix;
    $("#"+contentContainer).show()
    $("."  + container).click(function(){
        $(this).toggleClass("expand");
        $(this).toggleClass("collapse");
        thisId =  "#" + $(this).attr('id') + ';';
        containerId = "#" + $(this).attr('id') + postfix;
        $(containerId).slideToggle();	
    });
}

$.cbz.ui.accordian = function(container){
    $('#' + container).accordion({autoheight:false,header:".header",animated:"easeinout",alwaysOpen:false,active:false})
}


$.cbz.ui.tiptop = function(container, headerClassName, rowClassName) {
	$("." + container + " ." + rowClassName).hide();
	$("." + rowClassName + ":first").slideDown();
	$("." + headerClassName + ":first").addClass("active");
	
	$("." + container + " ." + headerClassName).click(function() {
		if (!$(this).hasClass("active")) {
			$("." + container + " ." + headerClassName).each(function(){
				$(this).removeClass("active");
			});															// Remove any "active" class
			$(this).addClass("active"); 								// Add "active" class to selected tabIndex
			
			if(!$.browser.msie){
				$("." + container + " ." + rowClassName).slideUp();			// slide up all the others
			}
			else {
				$("." + container + " ." + rowClassName).hide();			// hide all the others for IE
			}
			var activeTab = $(this).find("a").attr("href"); 			//Find the href
			if(activeTab.indexOf("http://") >= 0 ){						// IE returns the window url + hash
				tabvalue = activeTab.split("#");
				if(tabvalue[1] != null){
					activeTab = "#" + tabvalue[1];
				}
			}			
			$(activeTab).slideDown(1000);									// Fade in the active ID content
		}
		return false;
	});
}

$.cbz.stats = function(){}
$.cbz.stats.url = function(id,name){
	var url =""
	if(id!= null){
		link = "/stats/player/";
		if(!$.browser.msie){
			link += $.cbz.commons.sanitize(name) + "/";
		}		
		link +=  id;
		onclick= "return $.cbz.commonPopup(\"" + link + "\", \"Player Profile\", \"width=850,height=720\")"
		url += "<a title='" + name + " profile' href='Javascript:void(0);' onclick='" + onclick + " '>" + name + "</a>"
	}
	return url;
}

$.cbz.stats.url.cworld = function(id,name){
	var url =""
	if(id!= null){
		link = "/stats/player/";
		if(!$.browser.msie){
			link += $.cbz.commons.sanitize(name) + "/";
		}		
		link +=  id;
		onclick= "return $.cbz.commonPopup(\"" + link + "\", \"Player Profile\", \"width=850,height=720\")"
		url += "<a title='" + name + " profile' href='Javascript:void(0);' onclick='" + onclick + " '>" + name + "</a>"
	}
	return url;
}

$.cbz.getParameters = function(key){
cbz_parameters = $.cbz.getParametersArray();
return cbz_parameters[key];

}
$.cbz.getParametersArray = function(){
	cbz_paramsquery = window.location.search.substring(1)
	cbz_params = cbz_paramsquery.split("&");
	cbz_parameters = new Array('');
	for (i=0;i<cbz_params.length;i++) {
		keyvalues = cbz_params[i].split("=");
		key = keyvalues[0];
		value = keyvalues[1];
		cbz_parameters[key] = value;
	}
	return cbz_parameters;
}
$.cbz.util = function(){}
$.cbz.util.hoursDiff = function(date1,date2){
	if(date1 != "" && date1 != 0)
		date1Hours = parseInt(((new Date(date1).getTime())/1000)/(60*60));
	else
		date1Hours = 0;
	if(date2 != "" && date2 != 0)
		date2Hours = parseInt(((new Date(date2).getTime())/1000)/(60*60));
	else
		date2Hours = 0;
	diffHours = date1Hours - date2Hours
	return diffHours;
}
$.cbz.filter = function(data,prefTeam,previewHours,completionHours,considerDomestic,nextLive){
	returnData = data
	if(prefTeam != null && prefTeam != "")
		returnData = $.cbz.filter.prefTeam(data,prefTeam);
	if(previewHours != null)
		returnData = $.cbz.filter.previewMatches(returnData,previewHours);
	if(completionHours != null)
		returnData = $.cbz.filter.completionMatches(returnData,completionHours);
	if(considerDomestic != null)
		returnData = $.cbz.filter.isDomestic(returnData,considerDomestic);		
	if(returnData.length == 0 && nextLive != null){
		returnData = $.cbz.filter(nextLive,prefTeam,null,null,considerDomestic,null);
//		returnData = nextLive;
	}
/*
	if($.browser.msie) {
		returnData = returnData.reverse();
	}
*/
	return returnData;
}
$.cbz.filter.prefTeam = function(data,prefTeam){
	returnData = [];
	prefTeamMatchId = 0;
	 $(data).each(function(){
			if(this.matchId != null && this.matchId != undefined){
				if(this.team1.fullName == prefTeam || this.team2.fullName == prefTeam){
					prefTeamMatchId = this.matchId;
					this.matchIndex = 0;
					returnData.push(this);
					return false;
				}else{
					//this.matchIndex = this.matchId;
					this.matchIndex++;
				}	
			}
		})		
	$(data).each(function(){
			if(this.matchId != null && this.matchId != undefined && prefTeamMatchId != this.matchId){
					returnData.push(this);
			}
	})
	return returnData;
}
$.cbz.filter.previewMatches = function(data,previewHours){
	returnData = []
	 $(data).each(function(){
	 		if(this.matchId != null  && this.matchId != undefined && this.matchDataType != "Fixture"){
				previewDayAdd = 0;
				if(this.isPreviousDay){
					previewDayAdd = 24;
				}
				calcPreviewHours = $.cbz.util.hoursDiff(this.startdayandtimeGMT,this.matchcurrenttimeGMT) - previewHours - previewDayAdd;
				if(calcPreviewHours <= 0){
					returnData.push(this);
					//returnData[this.matchId] = this;
				}
			}
		});
	return returnData;
}
$.cbz.filter.completionMatches = function (data,complitionHours){
	returnData = []
	 $(data).each(function(){
			if(this.matchId != null  && this.matchId != undefined){
				calcCompletionHours = $.cbz.util.hoursDiff(this.matchcurrenttimeGMT,this.actualmatchendGMT)
				currentDate = $.cbz.util.hoursDiff(this.matchcurrenttimeGMT,0)
				if (calcCompletionHours == currentDate)
					calcCompletionHours = -1;
				if(calcCompletionHours <= complitionHours){
					returnData.push(this);
					//returnData[this.matchId] = this;
				}
			}
		});
	return returnData;
}
$.cbz.filter.isDomestic = function (data,considerDomestic){
	returnData = []
	 $(data).each(function(){
			if(this.matchId != null  && this.matchId != undefined){
				if(this.matchType == "International" || considerDomestic){
					returnData.push(this);
					//returnData[this.matchId] = this;
				}
			}
		});
	return returnData;
}
$.cbz.filter.removeSeries = function(data,seriesIds){
	returnData = [];
	 $(data).each(function(){
			if(this.matchId != null  && this.matchId != undefined){
				if($.inArray(this.seriesId, seriesIds) < 0){
					returnData.push(this);
				}
			}
		});
	return returnData;
}
$.cbz.commons.IPLfilter = function(string) {
	return string.ReplaceAll("Royal Challengers Bangalore","Bangalore").ReplaceAll("Bangalore Royal Challengers","Bangalore").ReplaceAll("Kolkata Knight Riders","Kolkata").ReplaceAll("Kings XI Punjab","Mohali").ReplaceAll("Kings XI Punjab","Mohali").ReplaceAll("Kings XI Punjab","Mohali").ReplaceAll("Chennai Super Kings","Chennai").ReplaceAll("Delhi Daredevils","Delhi").ReplaceAll("Rajasthan Royals","Jaipur").ReplaceAll("Mumbai Indians","Mumbai").ReplaceAll("Mumbai Indns","Mumbai").ReplaceAll("Deccan Chargers", "Hyderabad").ReplaceAll("Pune Warriors", "Pune").ReplaceAll("Kochi Tuskers Kerala", "kochi").ReplaceAll("Royal Challengers","Bangalore").ReplaceAll("Knight Riders","Kolkata").ReplaceAll("Kings XI","Mohali").ReplaceAll("Super Kings","Chennai").ReplaceAll("Daredevils","Delhi").ReplaceAll("RCB","Bangalore").ReplaceAll("RR","Jaipur").ReplaceAll("DD","Delhi").ReplaceAll("CSK","Chennai").ReplaceAll("KKR","Kolkata").ReplaceAll("Royals","Jaipur").ReplaceAll("Chargers", "Hyderabad").ReplaceAll("Indian Premier League","T20 League").ReplaceAll("IPL","T20 League").ReplaceAll("indian premier league","T20 League").ReplaceAll("ICC World Cup","WC");
}

String.prototype.ReplaceAll = function(stringToFind,stringToReplaceAll){
    var temp = this;

    var index = temp.indexOf(stringToFind);
	while(index != -1){
		temp = temp.replace(stringToFind,stringToReplaceAll);
		index = temp.indexOf(stringToFind);
	}
	return temp;
}
