function Ajax(url,DivID,val1,val2,val3,val4,val5,val6) {
	//alert(val1);
	$.ajax({
		type: 'POST',
		url : url,
		dataType :'html',
		data : {
			val1:val1,
			val2:val2,
			val3:val3,
			val4:val4,
			val5:val5,
			val6:val6,
			ajax_active:'set'
		},
		beforeSend:function(){
			$('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
		},
		complete:function(){
			$('.loadingWraper').remove();
		},
		success:function(page,textStatus){
			$('.loadingWraper').remove();
			if(DivID && DivID!=''){
                var data = $.parseJSON(page);
				$("#"+DivID).html(data.message);
			} else {
                if (textStatus == "success") {
                    if (document.getElementById('countdown_container') != null) {
                        abortCountDown = true;
                        document.getElementById('countdown_container').innerHTML = '';
                    }
                }
                alert(data.message);
            }
            //alert(data);
		},
        error: function () {
            alert("Please create an account and login to add media to your profile.");
        }
	});
}

// 1. used to display document content added to users profile.
function AjaxJson(url,DivID,val1,val2,val3,val4,val5,val6) {
	//alert(val1);
	$.ajax({
		url : url,
		dataType :'json',
		type: 'POST',
		data : {
			val1:val1,
			val2:val2,
			val3:val3,
			val4:val4,
			val5:val5,
			val6:val6,
			ajax_active:'set'
		},
		beforeSend:function(){
			$('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
		},
		complete:function(){
			$('.loadingWraper').remove();
		},
		success:function(data){
			$('.loadingWraper').remove();
            alert(data.message);
            if (data.mediaType == 'document')
                documentViewer(data.docId,data.userId);
            else if (data.mediaType == 'photo') {
                //photoViewer(data.docId,data.userId);
                if (data.fullImage != '')
                    document.getElementById('lightbox-image').src = data.fullImage;
            }
            //alert('Display Photo : '+data.docId+', '+data.userId);
		},
        error: function (data) {
            alert("Please create an account and login to add media to your profile.\n");
        }
	});
}

function PagingShorting(to,OrderBy,order) {
	var url=$('#url').val();
	var div=$('#div').val();
	var ShowRecord=$('#ShowRecord').val();
	var filterCondition=$('#filterCondition').val();
	$.ajax({
			type: 'POST',
			url:url,
			dataType:'html',
			data:{
				div:div,
				to:to,
				ShowRecord:ShowRecord,
				OrderBy:OrderBy,
				order:order,
				filterCondition:filterCondition,
				ajax_active:'set'
			},
			beforeSend:function(){
				$('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
			},
			complete:function(){
				$('.loadingWraper').remove();
			},
			success:function(data){
				$("#"+div).html(data);
			}
		});
}

function action(action,selected){
	if(selected){
		var flag = 0;
		$('form .checkbox').each(function(index){
			if(this.checked){
				flag=1;
			}
		});
		if(!flag){
			alert('Please select at least one check-box.');
			return false;
		}
	}
	if (action == 'Delete') {
		if (!confirm ('Delete cannot be undone! Are you sure you want to do this?')) {
			return false;
		}
	}
	$('form').submit();
}
function AnnouncementEchoed(UserId){
	if(UserId > 0){
		if (confirm ('Are you sure you want to echoed this announcement?')) {
			var url=baseUrl+'library/announcementEchoed/';
			Ajax(url,'',UserId);
			alert('You have echoed this annoncement sucessfully.');
		}
	}else{
		alert('Your loing session is expired! Please login again.');
	}
}

function UserAction(url,id){
		var flag = 0;
		var ID = 0;
		if(id > 0){
			flag=1;
			ID = id;
		}
		else{
			$('form .checkbox').each(function(index){
				if(this.checked){
					ID = ID+','+this.value;
					flag=1;
				}
			});
		}
		if(!flag){
			alert('Please select at least one check-box.');
			return false;
		}else{
			Ajax(url,'MessgeShow',ID);
		}
}

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function textViewer(caption, title, text, tokens, url, button) {
    Boxy.DEFAULTS.title = caption;
    var body = "<div style=\"width: 400px; padding: 3px;\"><br/>"+
               "  <p><strong>Title: </strong>"+title+"&nbsp;</p>"+
               "  <strong>Description: </strong>"+text+"<p><strong>"+
               "  Cost: </strong> "+tokens+"</p><p align=\"center\"><br/>";
    if (url.search("Ajax") >= 0) body += '<a href="#" onclick="'+url+'">';
    else body += "  <a href=\""+url+"\">";
    body += "<img src=\""+IMG+"button_instantaccess"+button+".png\" alt=\"Instant Access\" width=\"180\"/></a>"+
            "</p><br/></div>";
    new Boxy(body, { modal: true, behaviours: function(c) {}});
}

function instant_access(url) {
    Ajax(url);
}

function documentViewer(MediaId,UserId){
    Boxy.DEFAULTS.title = 'Docunent Viewer';
    $.ajax({
        type: 'POST',
        url:baseUrl+'library/documentShow/'+MediaId+'/'+UserId,
        dataType:'html',
        data:{ajax_active:'set'},
        beforeSend:function(){
            $('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
        },
        complete:function(){
            $('.loadingWraper').remove();
        },
        success:function(data){
            if(data){
                new Boxy("<div>"+data+"</div>", { modal: true, behaviours: function(c) {}});
            } else {
                new Boxy("<div><div class='info'>Empty "+Boxy.DEFAULTS.title+"</div></div>", { modal: true, behaviours: function(c) {}});
            }
            $('.closeBoxy').click(function() {
                location.reload();
            });
        }
    });
}

function photoViewer(MediaId,UserId){
    Boxy.DEFAULTS.title = 'Docunent Viewer';
    $.ajax({
        type: 'POST',
        url:baseUrl+'library/photoShow/'+MediaId+'/'+UserId,
        dataType:'html',
        data:{ajax_active:'set'},
        beforeSend:function(){
            $('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
        },
        complete:function(){
            $('.loadingWraper').remove();
        },
        success:function(data){
            if(data){
                Boxy("<div>"+data+"</div>", { modal: true, behaviours: function(c) {}});
            } else {
                Boxy("<div><div class='info'>Empty "+Boxy.DEFAULTS.title+"</div></div>", { modal: true, behaviours: function(c) {}});
            }
            $('.closeBoxy').click(function() {
                location.reload();
            });
        }
    });
}

function AddPlaylist(playlist){
	var flag = 0;
	Boxy.DEFAULTS.title = 'Playlist';
		var ID = 0;
		$('form .checkbox').each(function(index){
			if(this.checked){
				ID = ID+','+this.value;
				flag=1;
			}
		});
		if(!flag){
			alert('Please select media.');
			return false;
		}else{
			$.ajax({
				type: 'POST',
				url:baseUrl+'library/addPlaylist',
				dataType:'html',
				data:{ajax_active:'set'},
				beforeSend:function(){
					$('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
				},
				complete:function(){
					$('.loadingWraper').remove();
				},
				success:function(data){
					if(data){
						new Boxy("<div>"+data+"</div>", { modal: true, behaviours: function(c) {}});
					}
					else{
						new Boxy("<div><div class='info'>Empty "+Boxy.DEFAULTS.title+"</div></div>", { modal: true, behaviours: function(c) {}});
					}
					$('.closeBoxy').click(function() {
						location.reload();
					});
					$(".MyPlaylist").click(function(){
						var Title=$('#PlaylistTitle').val();
						if(Title ==''){
							alert('Please enter playlist title.');
							return false;
						}else{
								$.ajax({
									type: 'POST',
									url:baseUrl+'library/addPlaylist',
									dataType:'html',
									data:{
										TrackId:ID,
										playlist:playlist,
										Title:Title,
										ajax_active:'set'
									},
									beforeSend:function(){$('#PlaylistForm').html("<div id='ajxloading'><img src='"+IMG+"loading.gif'></div>");},
									success:function(data){
										$('#PlaylistForm').html(data);
										$('.closeBoxy').click(function() {
											location.reload();
										});
									}
								});
						}
					});
				}
			});
		}

}

function deletePlaylist(url){
	if(confirm('Do you realy want to delete this playlist?')){
		Ajax(url,'MessgeShow');
		$('#librarylisting').remove();
	}
}

function deleteMedia(url,tag){
	if(tag!='td'){
		tag='tr';
	}
	var flag = 0;
	$('form .checkbox').each(function(index){
		if(this.checked){
			ID = parseInt(this.value);
			if(ID > 0){
				if(flag == 0){
					if(!confirm('Do you realy want to delete this?')){
						return false;
					}
				}
				flag = 1;
				Ajax(url,'MessgeShow',ID);
				$(this).parents(tag+':first').remove();
			}
		}
	});
	if(!flag){
		alert('Please select at least one check-box.');
		return false;
	}else{
		return true;
	}
}
function promotPlaylist(ID){
	var url=baseUrl+'library/promotPlaylist';
	if(!ID > 0){
		alert('Some internal problem. please try after some time');
	}else{
		Ajax(url,'MessgeShow',ID);
	}
}
function downloadPlaylist(){
	var flag = 0;
	//var url=baseUrl+'library/getPlaylist';
	var userTokenBalance= parseInt($('#userTokenBalance').val());
	var HP= parseInt($('#HP').val());
	var loggedUserId= parseInt($('#loggedUserId').val());
	var UserId= parseInt($('#UserId').val());
	if(userTokenBalance <  HP){
		alert('Insufficient token balance');
		return false;
	}else{
		//$('form').attr('action',url);
		//$('#form').submit();
			var PlaylistId=$('#PlaylistId').val();
			var TrackId=$('#TrackId').val();
			var UserId=$('#UserId').val();
			var url=baseUrl+'library/getPlaylist/'+PlaylistId+'/'+TrackId+'/'+UserId;
			var popupWindow= window.open(url, "_blank", "status=true,toolbar=false,menubar=false,location=true,width=350,height=350")
			 if (popupWindow=== null) {
				alert("A messasge to inform the user, that the popup has been blocked");
				return false;
			}else{
				userTokenBalance=(userTokenBalance-HP);
				document.getElementById('userTokenBalance').value=userTokenBalance;
			}
	}
}
function downloadMedia(){
	/*commented on date 03-03-2011
	var flag = 0;
	var url=baseUrl+'library/getMedia';
	$('form .checkbox').each(function(index){
		if(this.checked){
			flag = 1;
		}
	}); */

	/* Start Added on date 03-03-2011 */
		var flag=0,HP=0;
		var ID;
		var TrackId='';
		$('form .checkbox').each(function(index){
			if(this.checked){
				flag = 1;
				TrackId = TrackId+'_'+this.value;
				ID=this.id;
				Val=ID.split('|');
				HP=(HP + parseInt(Val[1]));

			}
		});
	/*End Added on date 03-03-2011 */

	if(!flag){
		alert('Please select atleast one check-box.');
		return false;
	}else{

	  /*commented on date 03-03-2011
	  $('form').attr('action',url);
	  $('#form').submit();*/

	 /* Start Added on date 03-03-2011 */
			var userTokenBalance= parseInt($('#userTokenBalance').val());

			if(userTokenBalance <  HP){
				alert('Insufficient token balance');
				return false;
			}else{
					var url=baseUrl+'library/getMedia/'+TrackId;
					var popupWindow= window.open(url, "_blank", "status=true,toolbar=false,menubar=false,location=true,width=350,height=350")
					 if (popupWindow=== null) {
						alert("A messasge to inform the user, that the popup has been blocked");
						return false;
					}else{
						userTokenBalance=(userTokenBalance-HP);
						document.getElementById('userTokenBalance').value=userTokenBalance;
					}
			}
		/*End Added on date 03-03-2011 */
	}
}
function Calculate(obj,CalculationType){
	var flag=0,TV=0,HP=0,AD=0,DL=0;
	var ID;
	$('form .checkbox').each(function(index){
		if(this.checked){
			flag = 1;
			ID=this.id;
			Val=ID.split('|');
			TV=(TV + parseInt(Val[0]));
			HP=(HP + parseInt(Val[1]));
			AD=(AD + parseInt(Val[2]));
			DL=(DL + parseInt(Val[3]));
		}
	});
	if(!flag){
		obj.title='Please select at least one media';
	}else{

		if(CalculationType=='AddDownload'){
			obj.title='Added|Downloaded: '+AD+'|'+DL;
		}
		else if(CalculationType=='TokenPrice'){
			obj.title='Add Price: '+TV+' Token';
		}
		else if(CalculationType=='HardcorePrice'){
			obj.title='Download Price: '+HP+' Token';
		}
		$('.mediaImg').tipsy({gravity: 'n'});
	}
}
function otherValue(obj){
	//alert(obj);
	var name='other'+obj.name;
	if(obj.value=='other'){
		$(obj).parent().append('<div class="pt10" id="'+name+'"><label for="'+name+'" class="require_field">Other:</label><input name="'+name+'" type="text" value="" class="required" minLength="2" maxLength="20" /></div>');
	}
	else{
		$('#'+name).remove();
	}
}
function Topchart(obj, url){
	var id=obj.id;
	var time=$('#Time').val();
	var genre=$('#Genre').val();
	url=url+'/'+time+'/'+genre;
	$('span[id*="'+id+'"]').attr('class', '');
	$(obj).attr('class', 'b');
	Ajax(url,'TopChartResult');
}

function playlist(obj,UserId){
	var id=obj.value
	if(id > 0){
		var url=baseUrl+'library/playlistItem/'+id+'/'+UserId;
		$('a[id*="Mediaab"]').attr('class', '');
		$(obj).parents('a:first').attr('class', 'selected');
		Ajax(url,'MediaListDiv');
	}
}

function MyStatisics(obj, url){
	var id=obj.id;
	$('a[id*="'+id+'"]').attr('class', '');
	$(obj).attr('class', 'selected');
	Ajax(url,'myStatisticsDiv');
}

function popwindow(url,width,height){
	window.open(
		""+baseUrl+""+url,
		"media",
		"width="+width+",height="+height+",scrollbars=yes,status=no,resizable=yes,screenx=0,screeny=0"
	)
}

function playMedia(UserId,divId,TrackId,delivered,title){
    //alert(TrackId);
    var flag = 0;
    var media_title = title;
    if(!(delivered > 0)){
        delivered=0;
    }
    if((TrackId != undefined) && (TrackId != 'undefined')){
        flag=1;
    }
    else{
        TrackId=0;
        $('form .checkbox').each(function(index){
            if(this.checked){
                var input = this.value;
                var data  = input.split(",");
                media_title = data[1];
                TrackId = TrackId+'_'+data[0];
                flag=1;
            }
        });
    }
    if(!flag){
        alert('Please select at least one check-box.');
        //return false;
    }
    else{
            var url='library/playmedia/'+TrackId+'/'+UserId+'/'+delivered+'/'+media_title;
            popwindow(url,1020,700);

                    /*$.ajax({
                        type: 'POST',
                        url:baseUrl+'library/playmedia',
                        dataType:'html',
                        data:{
                            TrackId:TrackId,
                            UserId:UserId,
                            ajax_active:'set'
                        },
                        beforeSend:function(){
                            $("#"+divId).html("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
                        },
                        complete:function(){
                            //$("#"+divId).html('');
                        },
                        success:function(data){
                            if(divId=='playercontent'){
                                $("#"+divId).html(data);
                            }
                            else{
                                Boxy.DEFAULTS.title = 'Play';
                                if(data){
                                    new Boxy("<div>"+data+"</div>", { modal: true, behaviours: function(c) {}});
                                }
                                else{
                                    new Boxy("<div><div class='info'>Empty "+Boxy.DEFAULTS.title+"</div></div>", { modal: true, behaviours: function(c) {}});
                                }
                                $('.closeBoxy').click(function() {
                                    location.reload();
                                });
                            }
                        }
                    });*/
    }
}

function deliverMedia(Media,id){

	var flag = 0;
	Boxy.DEFAULTS.title = 'select users you would like to send a delivery to';
		var ID = 0;
		var UserId='';
		if(id > 0){
			flag=1;
			ID = id;
		}
		else{
			$('form .checkbox').each(function(index){
				if(this.checked){
					ID = ID+','+this.value;
					flag=1;
				}
			});
		}
		if(!flag){
			alert('Please select at least one check-box.');
			return false;
		}else{
			$.ajax({
				type: 'POST',
				url:baseUrl+'library/deliverMedia',
				dataType:'html',
				data:{
					TrackId:ID,
					Media:Media,
					ajax_active:'set'
				},
				beforeSend:function(){
					$('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
				},
				complete:function(){
					$('.loadingWraper').remove();
				},
				success:function(data){
					if(data){
						new Boxy("<div>"+data+"</div>", { modal: true, behaviours: function(c) {}});
					}
					else{
						new Boxy("<div><div class='info'>Empty "+Boxy.DEFAULTS.title+"</div></div>", { modal: true, behaviours: function(c) {}});
					}
					$(".SendDelivery").click(function(){
						//alert('hi');
						var flag = 0;
						$('form .userCheckbox').each(function(index){
							if(this.checked){
								UserId = UserId+','+this.value;
								flag = 1;
							}
						});
						if(!flag){
							alert('Please select at least one check-box.');
							return false;
						}else{
								$.ajax({
									type: 'POST',
									url:baseUrl+'library/deliverMedia',
									dataType:'html',
									data:{
										deliverySend:$('#deliverySend').val(),
										UserId:UserId,
										TrackId:$('#TREACKID').val(),
										Media:$('#MEDIA').val(),
										ajax_active:'set'
									},
									beforeSend:function(){$('#DeliverySends').html("<div id='ajxloading'><img src='<?PHP echo IMG;?>/loading.gif'></div>");},
									success:function(data){
										$('#DeliverySends').html(data);
									}
								});
						}
					});
				}
			});
		}

}
function notifyingEmail(){
	var flag=0;
	var ID=0;
	$('form .checkbox').each(function(index){
		if(this.checked){
			ID = ID+','+this.value;
			flag=1;
		}
	});
	if(!flag){
		alert('Please select at least one check-box.');
		return false;
	}
	else
	if(confirm('Do you realy want to Sent email notifying of inappropriate/copyrighted to administrator?')){
		url=baseUrl+'library/notifyingEmail',
		Ajax(url,'MessgeShow',ID);
	}
}

function followUnfollow(obj){
	 var action = $(obj).html();
	 var userId = obj.id;
	$.ajax({
		type: 'POST',
		url:baseUrl+'user/followme',
		data:{val1:userId,val2:action,ajax_active:'set'},
		beforeSend:function(){
			$('body').append("<div class='loadingWraper'><div id='ajxloading'><img src='"+IMG+"loading.gif'></div></div>");
		},
		complete:function(){
			$('.loadingWraper').remove();
		},
		success:function(data){
			if(action =='Follow Me')
				$(obj).html('Unfollow Me');
			else
				$(obj).html('Follow Me');
		}
	});
}




var timeout	= 200;
var closetimer	= 0;
var ddmenuitem	= 0;

// open hidden layer
function mopen(id){
	// cancel close timer
	mcancelclosetime();

	// close old layer
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';

	// get new layer and show it
	ddmenuitem = document.getElementById(id);
	ddmenuitem.style.visibility = 'visible';

}
// close showed layer
function mclose()
{
	if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
}

// go close timer
function mclosetime()
{
	closetimer = window.setTimeout(mclose, timeout);
}

// cancel close timer
function mcancelclosetime()
{
	if(closetimer)
	{
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

// close layer when click-out
document.onclick = mclose;

function showMediaHover(userid)
{
	$('.mediaItem_hover'+userid).toggle();
    //$("a.screenshot").lightbox();
}

function pausecomp(ms) {
    ms += new Date().getTime();
    while (new Date() < ms){}
}

