﻿var scrollPos = 0;
var dmgPlayerToogle = false;
var ShowMore = false;
var SubNavTime = true;
var StationListTime = true;
var SelectedNav;
  
$(document).ready(function(){

InitDMG();
$("#AjaxLoading").ajaxStart(function(){$(this).show();});
$("#AjaxLoading").ajaxStop(function(){$(this).hide();});

$("#HeaderLogout").click(function(event){
    $("#PMAlert").hide(200);
    $("#LogoutAlert").show(500);
    LogoutAlertHide();
    event.preventDefault();
});
$("#LogoutNo").click(function(event){
    $("#LogoutAlert").hide();
    LogoutAlertTime = false;
    event.preventDefault();
});
$("#LogoutAlert").hover(function(){ LogoutAlertResetTimeout(); });
$("#LogoutAlert").mouseleave(function(){ LogoutAlertHide(); });

$("#menu ul li a").hover(function(){ ShowSubNav($(this).text(), $(this).position()); });
$("#menu ul li a").mouseleave(function(){ SubNavTimeHide(); });
$(".NavItem").hover(function(){ SubNavResetTimeout(); });
$(".NavItem").mouseleave(function(){ SubNavTimeHide(); });

$(".SummaryTabs a").click(function(event){
    if (!$(this).hasClass("selected")) {
    $(this).siblings().removeClass();
    $(this).addClass("selected");
    $(this).parent().siblings().each(function (i) {
        if ($(this).hasClass("TabShow")) {
            $(this).removeClass("TabShow");
            $(this).addClass("TabHide");
        }
        else {
            $(this).removeClass("TabHide");
            $(this).addClass("TabShow");
        }   
    });
    }
    event.preventDefault();
});
$(".SummaryTabsB a").click(function(event){
    $(this).siblings().removeClass("selected");
    $(this).addClass("selected");
    jQuery.each($(this).siblings("a"), function() {
        $("#Summary" + $(this).attr("title")).hide();
    });
    $("#Summary" + $(this).attr("title")).show();
    event.preventDefault();
});

$("#ShowAllStations").hover(function(event){
 /* $("#StationList").css({'top': $(this).position().top + 15, 'left': $(this).position().left});*/
  $("#StationList").fadeIn(350);
});
$("#ShowAllStations").mouseleave(function(){StationListHide();});
$("#StationList").hover(function(){ StationListResetTimeout(); });
$("#StationList").mouseleave(function(){ StationListHide(); });
     
$(".BoxHide").click(function(event){
  $(this).parent().slideToggle();
  event.preventDefault();
});
  
$(".MoreBox").click(function(event){
  if (scrollPos == 2) {
    $("#GalleryList").animate({top: "0"});  scrollPos=0;
    return false;
  }
  $("#GalleryList").animate({top: "-=120"});
  scrollPos += 1;
  // on the fouth one, scroll to the top
  event.preventDefault();
});
    
$(".PullDown").click(function(event){
  if (scrollPos == 2) {
    $("#GalleryList").animate({top: "0"});  scrollPos=0;
    return false;
  }
  $("#GalleryList").animate({top: "+=120"});
  scrollPos += 1;
  // on the fouth one, scroll to the top
  event.preventDefault();
});
        
$("#PlayListMore").click(function(event){
	
   !dmgPlayerToogle ? $("#DMGPlayList").animate({top: "+=240"}) : $("#DMGPlayList").animate({top: "-=240"});
    dmgPlayerToogle = !dmgPlayerToogle;
    event.preventDefault();
});

$("#ContentSections a").click(function(event){
  ResetSection();
  $(this).addClass("Selected");
  event.preventDefault();
});

$("#ContentSections a#NewMessage").click(function(event){
    window.location="messagenew";
});

// ::Menu > Nav > Recent/Popular Articles   <---- can we standardise this?  looks like a bit of repeat.
if($("#ArticleContainer").html() != null){
    $("#NavRecentArticles").click(function(event){
        GetArticles("recent");
        $("#ContentSections a").removeClass();
        $("#ButtonRecent").addClass("Selected");
        event.preventDefault();
    });
    $("#NavPopularArticles").click(function(event){        
        GetArticles("popular");
        $("#ContentSections a").removeClass();
        $("#ButtonPopular").addClass("Selected");
        event.preventDefault();
    });
    $("#NavFavedArticles").click(function(event){        
        GetArticles("fave");
        $("#ContentSections a").removeClass();
        $("#ButtonFaved").addClass("Selected");
        event.preventDefault();
    });
}
if($("#GalleryContainer").html() != null){
    $("#NavRecentAlbums").click(function(event){
        Mode="gallery";
        GetPhotos();
        $("#ContentSections a").removeClass();
        $("#GalleryRecent").addClass("Selected");
        event.preventDefault();
    });
    $("#NavRecentPhotos").click(function(event){   
        Mode="photo";
        GetPhotos(); 
        $("#ContentSections a").removeClass();
        $("#PhotoRecent").addClass("Selected");
        event.preventDefault();
    });
    $("#NavPopularPhotos").click(function(event){   
        Mode="popular";
        GetPhotos();
        $("#ContentSections a").removeClass();
        $("#PhotoPopular").addClass("Selected");
        event.preventDefault();
    });
}
if($("#VideoContainer").html() != null){
    $("#NavRecentVideos").click(function(event){
        GetVideos("recent","list");      
        $("#ContentSections a").removeClass();
        $("#ButtonRecent").addClass("Selected");
        event.preventDefault();
    });
    $("#NavPopularVideos").click(function(event){        
        GetVideos("popular","list");
        $("#ContentSections a").removeClass();
        $("#ButtonPopular").addClass("Selected");
        event.preventDefault();
    });
}
if($("#ForumDiscussionPanel").html() != null){
    $("#NavRecentForum").click(function(event){
        ForumQ = "recent";
        GetDiscussions();
        $("#ForumPager").show();
        $("#ContentSections a").removeClass();
        $("#ForumLatest").addClass("Selected");
        event.preventDefault();
    });
    $("#NavPopularForum").click(function(event){        
        ForumQ = "popular";
        GetDiscussions();
        $("#ForumPager").show();
        $("#ContentSections a").removeClass();
        $("#ForumPopular").addClass("Selected");
        event.preventDefault();
    });
}
if($("#AudioContaniner").html() != null){
    $("#NavRecentAudios").click(function(event){
        GetAudios("recent");
        $("#ContentSections a").removeClass();
        $("#ButtonRecent").addClass("Selected");
        event.preventDefault();
    });
    $("#NavPopularAudios").click(function(event){        
        GetAudios("popular");
        $("#ContentSections a").removeClass();
        $("#ButtonPopular").addClass("Selected");
        event.preventDefault();
    });
}


$("#DMGGoogleAdFloat").hover(function() {
    $("#DMGGoogleAdFloat").stop().animate({ right: "+311px" }, { queue: false, duration: 200 });
}, function() {
    $("#DMGGoogleAdFloat").stop().animate({ right: "112px" }, { queue: false, duration: 200 });
});

});  
      
function InitDMG() {
  $("#Hero .Heroes:not(:first)").hide();
  $(".NavItem").hide();
  $(".whatsHappening .whatsHappeningInner:first").addClass("first");
  
  if ($('#lblMessageCount').text() == "no") {
      setTimeout("$('#PMAlert').fadeOut(500)", 5000);
  }
  
  expandFloatAd();

  window.setTimeout(function() {
      collapseFloatAd();
  }, 3000);
}


function collapseFloatAd() {
    $("#DMGGoogleAdFloat").stop().animate({ right: "112px" }, { queue: false, duration: 200 });
}

function expandFloatAd() {
    $("#DMGGoogleAdFloat").stop().animate({ right: "+311px" }, { queue: false, duration: 200 });
}

function ShowSubNav(subnav, position) {
  //$("#m-"+subnav).css({'background-position': '0px 1px'});
  SubNavHide();
  SubNavResetTimeout();
  $("#More"+subnav).css({'top': position.top + 37, 'left': position.left});
  $("#More"+subnav).show();
}

function SubNavTimeHide() {
  SubNavTime = true;
  setTimeout("if (SubNavTime) { $('.NavItem').fadeOut(100); }", 500) 
}
function SubNavResetTimeout() { SubNavTime = false; }
function SubNavHide() { $(".NavItem").hide(); }

function StationListHide() {
  StationListTime = true;
  setTimeout("if (StationListTime) { $('#StationList').fadeOut(100); }", 500) 
}
function StationListResetTimeout() { StationListTime = false; }

function LogoutAlertHide() {
  LogoutAlertTime = true;
  setTimeout("if (LogoutAlertTime) { $('#LogoutAlert').fadeOut(100); }", 3000) 
}
function LogoutAlertResetTimeout() { LogoutAlertTime = false; }

function ResetSection() {
  $("#ContentSections a").removeClass();
}

/*************** tag suggest *******************/
function FillTag(tagContainer, tagBoxName)
{   
     var tagBox = document.getElementById(tagBoxName);
     var tag = tagContainer.innerHTML;
     // if it finds the tag
     if (tagBox.value.indexOf(tag) != -1)
     {
        if (tagBox.value.indexOf(','+tag) != -1){
            tagBox.value = tagBox.value.replace(','+tag, '');
            tagContainer.className = "";
        }
        if (tagBox.value.indexOf(tag+',') != -1){
            tagBox.value = tagBox.value.replace(tag+',', '');
            tagContainer.className = "";
        }
        if(tagBox.value.indexOf(tag) != -1){
            tagBox.value = tagBox.value.replace(tag, '');
            tagContainer.className = "";
        }
     }
     else 
     {
        if (tagBox.value.length > 0){tagBox.value += ',' + tag;}
        else{tagBox.value = tag;}        
        tagContainer.className = "selected";
    }    
//    tagBox.value = tagBox.value.replace("  ", ' ');
    $.trim(tagBox.value);
}
function FillMate(tagContainer, tagBoxName)
{   
    var tagBox = document.getElementById(tagBoxName);
    var tag = tagContainer.innerHTML;
    tagBox.value = tag;
    $.trim(tagBox.value);
}

/*** user action *** */
function doFave(){$.ajax({url: "ajax/FaveHandler.ashx",data:favePars,success:onFaveSuccess});}
function onFaveSuccess(txt){	
    var result = txt;
    var lbFaveError = $('#lbFaveError'); // error message
    if(result == 'invalid_params')lbFaveError.html("invalid params");
    else if(result == 'update_err')lbFaveError.html("voting error");
    else if(result == 'has_faved'){phFaveAction.hide('slow');}
    else{lbFaveError.html("added to favourites");}
}
function doRate(rating){$.ajax({url: "ajax/RatingHandler.ashx",data:ratePars+"&r="+rating,success:onRateSuccess});}
function onRateSuccess(result){	
    if(result == 'invalid_params'){$('#lbRateError').html("invalid params");}
    else if(result == 'update_err'){$('#lbRateError').html("rating error");}
    else{
        $('#lbRateError').html("");    
        $("#StarRating").fadeIn("slow");
        $('input.star').rating('setRating',result);
        $('input.star').rating('disable');
        $('#lbRateError').html("rating submitted");
    }
}
function doAudioRate(rating){$.ajax({url: "ajax/RatingHandler.ashx",data:ratePars2+"&r="+rating,success:onAudioRateSuccess});}
function onAudioRateSuccess(result){
    if(result == 'invalid_params'){jAlert("invalid params",'Error');}
    else if(result == 'update_err'){jAlert("rating error",'Error');}
    else{
        $("#StarRating2").fadeIn("slow");
        $('input.star2').rating('setRating',result);
        $('input.star2').rating('disable');
    }
}
function doSongFave(userId,itemId,obj){
    $.ajax({url: "ajax/FaveHandler.ashx",data:"u="+userId+"&i="+itemId+"&t=7",success:function(txt){
            var result = txt;
            if(result == 'invalid_params'){jAlert("invalid params",'Error');}
            else if(result == 'update_err'){jAlert("favorite error",'Error');}
            else if(result == 'has_faved'){/*jAlert("already favorite ",'Error');*/}
            else{$(obj).attr('className','addedTofav');/*jAlert("added to favourites","Success");*/}
        }
    });
}

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*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

function resizePictures(objPosts){
    var ForumPane = document.getElementById(objPosts);
    var images = ForumPane.getElementsByTagName('img');
    for (var i=0; i<images.length; i++){
	    var img = images[i];
		reSize(img,500,500);
    }
}
function reSize(myImg, maxWidth, maxHeight)
{
	var iniPicWidth = myImg.width;
	var iniPicHeight = myImg.height;
	var iniRate = iniPicHeight/iniPicWidth;
	if(iniPicWidth>maxWidth || iniPicHeight>maxHeight){
		var newW = maxWidth;
		var newH = Math.floor(newW*iniRate);
		if (newH>maxHeight)
		{
			var newH = maxHeight;
			var newW = Math.floor(newH/iniRate);
		}
		myImg.width = newW;
		myImg.height = newH;
	}
}
function stripTags(s){
	s = s.replace(/<br \/>/gi,"\r");
	s = s.replace(/<br\/>/gi,"\r");
	s = s.replace(/<br>/gi,"\r");
	s = s.replace(/<i>/gi,"");
	s = s.replace(/<\/i>/gi,"");
	s = s.replace(/<b>/gi,"");
	s = s.replace(/<\/b>/gi,"");
	s = s.replace(/<blockquote>/gi,"[quote]");
	s = s.replace(/<\/blockquote>/gi,"[/quote]");
	s = s.replace(/<p>/gi,"");
	s = s.replace(/<\/p>/gi,"");
	s = s.replace(/<a[\s]*target=\"_blank\"[\s]*rel=\"nofollow\"[\s]*href=\"[\w.\?=_\-\/:]+\">/gi,"");
	s = s.replace(/<\/a>/gi,"");
	s = s.replace(/<img[\s]*class=\"Thumb\"[\s]*src=\"([^\"]*)*\"[^>]*>/gi,"[img]$1[/img]");
    s = s.replace(/<.*\/>/gi,"");
    s = s.replace(/<.*>/gi,"");
    s = s.replace(/<\/.*>/gi,"");
    s = s.replace(/[\n]+/gi,"\r");
    while(s != s.replace(/\r[\s]*\r/gi,"\r")){
        s = s.replace(/\r[\s]*\r/gi,"\r");
    }
    return s;
}
function Quote(username,contentId, textBoxId){
    var objTextBox = document.getElementById(textBoxId);
    var content = document.getElementById(contentId).innerHTML;
    content = stripTags(content);
    var quote = "[quote][b]" + username + " said:[/b] " + content + "[/quote]\r";
    objTextBox.value = objTextBox.value + quote;
    objTextBox.focus(); 
}
// Streaming
function OpenStreaming(url){
    var test = window.open(url,'Streaming','left=20,top=20,width=750,height=600,toolbar=0,resizable=0');
}
//Stats
function statsTracker() {
    //google
    try {
        pageTracker._trackPageview(); //google
        trac.record().post(); //nielsen
    } catch (err) { }
}

jQuery.fn.exists = function() { return jQuery(this).length > 0; }