﻿var scrollPos = 0;
var dmgPlayerToogle = false;
var ShowMore = false;
var SubNavTime = true;
var StationListTime = true;
var SelectedNav;

//google analytics vars
var ga_PillarsArray = [];
var ga_AuthorsArray = [];
var ga_SourceId = "";
var ga_GalleryName = "";

$(document).ready(function() {


    InitDMG();
    $("#AjaxLoading").ajaxStart(function() { $(this).show(); });
    $("#AjaxLoading").ajaxStop(function() { $(this).hide(); });

    $("#HeaderLogout").click(function(event) {
        $("#PMAlert").fadeOut(200);
        $("#LogoutAlert").fadeIn(500);
        LogoutAlertHide();
        event.preventDefault();
    });
    $("#LogoutNo").click(function(event) {
        $("#LogoutAlert").fadeOut(200);
        $("#PMAlert").fadeIn(500);
        LogoutAlertTime = false;
        event.preventDefault();
    });



    $("#LogoutAlert").hover(function() { LogoutAlertResetTimeout(); });
    $("#LogoutAlert").mouseleave(function() { LogoutAlertHide(); });




    /* Hide main navigation javascript

        var Nav = {};
    Nav.currentList;
    Nav.currentItem;

        $("#menu ul li a").hover(function() { ShowSubNav($(this).text(), $(this).position()); Nav.currentItem = $("#More" + $(this).text()); });
    $("#menu ul li a").mouseleave(function() { SubNavTimeHide(); });

        $("#menu ul li").hover(function() { $(this).addClass('active'); Nav.currentList = this; });
    $("#menu ul li").mouseleave(function() {});

        $(".NavItem").hover(function() { SubNavResetTimeout(); });
    $(".NavItem").mouseleave(function() { SubNavTimeHide(); });
    
    */


    $(".SummaryTabs 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();
    });


    /** -----------------------------
    Gallery Port on homapge 
    ------------------------------**/

    var GalleryPort = {};
    GalleryPort.maxVisible = 12; //set max visible here


    (function initGalleryPort(maxVisible) {
        for (i = maxVisible; i < $('#GalleryPort #GalleryList li').length; i++) {
            $('#GalleryPort #GalleryList li:eq(' + i + ')').css('display', 'none');
        }

        $('#GalleryPort a.up').fadeTo(100, 0.2);


        GalleryPort.maxVisible = maxVisible;
        GalleryPort.maxPage = Math.ceil($('#GalleryPort #GalleryList li').length / maxVisible);
        GalleryPort.current = 1;

        if (GalleryPort.current >= GalleryPort.maxPage) {
            $('#GalleryPort a.down').fadeTo(100, 0.2);
        }
    })(GalleryPort.maxVisible);


    $('#GalleryPort a.up').click(function() {
        if (GalleryPort.current == 1) {
            return false;
        } else {
            for (i = ((GalleryPort.current * GalleryPort.maxVisible) - GalleryPort.maxVisible); i < (GalleryPort.current * GalleryPort.maxVisible); i++) {
                $('#GalleryPort #GalleryList li:eq(' + i + ')').css('display', 'none');
                if ($('#GalleryPort #GalleryList li:eq(' + (i - GalleryPort.maxVisible) + ')')) {
                    $('#GalleryPort #GalleryList li:eq(' + (i - GalleryPort.maxVisible) + ')').css('display', 'block');
                }
            }
            $('#GalleryPort a.down').fadeTo(100, 1);
            GalleryPort.current -= 1;
            if (GalleryPort.current == 1) {
                $('#GalleryPort a.up').fadeTo(100, 0.2);
            }
        }
    });



    $('#GalleryPort a.down').click(function() {
        if ((GalleryPort.current * GalleryPort.maxVisible) >= $('#GalleryPort #GalleryList li').length) {
            return false;
        } else {
            for (i = ((GalleryPort.current * GalleryPort.maxVisible) - GalleryPort.maxVisible); i < (GalleryPort.current * GalleryPort.maxVisible); i++) {
                $('#GalleryPort #GalleryList li:eq(' + i + ')').css('display', 'none');
                $('#GalleryPort #GalleryList li:eq(' + (i + GalleryPort.maxVisible) + ')').css('display', 'block');
            }

            $('#GalleryPort a.up').fadeTo(100, 1);
            GalleryPort.current += 1;
            if (GalleryPort.current == GalleryPort.maxPage) {
                $('#GalleryPort a.down').fadeTo(100, 0.2);
            }
        }
    });

    /** ---------------------------------- **/


    $("#PlayListMoreNovaNation").click(function(event) {
        !dmgPlayerToogle ? $("#DMGPlayList").animate({ top: "+=267" }) : $("#DMGPlayList").animate({ top: "-=267" });
        dmgPlayerToogle = !dmgPlayerToogle;
        event.preventDefault();
    });

    $("#PlayListMoreKoffee").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";
            GetPageCount();
            GetPhotos();
            $("#ContentSections a").removeClass();
            $("#GalleryRecent").addClass("Selected");
            event.preventDefault();
        });
        $("#NavRecentPhotos").click(function(event) {
            Mode = "photo";
            GetPageCount();
            GetPhotos();
            $("#ContentSections a").removeClass();
            $("#PhotoRecent").addClass("Selected");
            event.preventDefault();
        });
        $("#NavPopularPhotos").click(function(event) {
            Mode = "popular";
            GetPageCount();
            GetPhotos();
            $("#ContentSections a").removeClass();
            $("#PhotoPopular").addClass("Selected");
            event.preventDefault();
        });
        $("#NavUserPhotos").click(function(event) {
            Mode = "user";
            GetPageCount();
            GetPhotos();
            $("#ContentSections a").removeClass();
            $("#UserPhotos").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();
        });
    }

    $("#DMGGoogleAdFloatNovaNation").hover(function() {
        $("#DMGGoogleAdFloatNovaNation").stop().animate({ right: "+300px" }, { queue: false, duration: 200 });
        }, function() {
        $("#DMGGoogleAdFloatNovaNation").stop().animate({ right: "141px" }, { queue: false, duration: 200 });
    });

    $("#DMGGoogleAdFloatKoffee").hover(function() {
        $("#DMGGoogleAdFloatKoffee").stop().animate({ right: "+311px" }, { queue: false, duration: 200 });
        }, function() {
        $("#DMGGoogleAdFloatKoffee").stop().animate({ right: "112px" }, { queue: false, duration: 200 });
    });

    $("#DMGGoogleAdFloatFiveAA").hover(function() {
        $("#DMGGoogleAdFloatFiveAA").stop().animate({ right: "+272px" }, { queue: false, duration: 200 });
        }, function() {
        $("#DMGGoogleAdFloatFiveAA").stop().animate({ right: "112px" }, { queue: false, duration: 200 });
    });


});  
      
      
      
      

function InitDMG() {
  $("#Hero .Heroes:not(:first)").hide();
 /* $(".NavItem").hide();*/
  if($('#lblMessageCount').text()=="no"){
    setTimeout("$('#PMAlert').fadeOut(500)", 5000); 
  }
}

function ShowSubNav(subnav, position) {
  SubNavHide();
  SubNavResetTimeout();
  //alert(position.top);
  $("#More"+subnav).css({'top': position.top + 229, 'left': position.left - 1});
  $("#More"+subnav).show();
}

function SubNavTimeHide() {
  SubNavTime = true;
  //$.timer(500, function (timer) {
  //  if (SubNavTime) { $(".NavItem").fadeOut(100); }
  //  timer.stop();
  //});
  setTimeout("if (SubNavTime) { $('.NavItem').fadeOut(100); $('#menu ul li').removeClass('active'); }", 500) 
  //$("#m-"+subnav).css({'background-position': '0px 50px'});
}
function SubNavResetTimeout() { SubNavTime = false; }
function SubNavHide() { $(".NavItem").hide(); $('#menu ul li').removeClass('active'); }

function StationListHide() {
  StationListTime = true;
  setTimeout("if (StationListTime) { $('#StationList').fadeOut(100); }", 500) 
}
function StationListResetTimeout() { StationListTime = false; }

function LogoutAlertHide() {
  LogoutAlertTime = true;
  setTimeout("if (LogoutAlertTime) { $('#LogoutAlert').fadeOut(400); $('#PMAlert').fadeIn(800); }", 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_voted'){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");
        if ($('input.star2').length != 0) {
            $('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(); 
}
function clickButton(e, buttonid){
  var evt = e ? e : window.event;
  var bt = document.getElementById(buttonid);
  if (bt){
      if (evt.keyCode == 13){
            bt.click();
            return false;
      }
  }
}

// Streaming
function OpenStreaming(url){
    //var test = window.open(url, 'Streaming', 'left=20,top=20,width=750,height=600,toolbar=0,resizable=0');
    var test = window.open(url, 'Streaming', 'left=20,top=20,width=750,height=600,menubar=no,location=no,resizable=no,scrollbars=no,status=no');
}

//Stats
function statsTracker() {
    //google
    try {
        _gaq.push(['_trackPageview']); //google
        trac.record().post(); //nielsen
    } catch (err) { }
}

jQuery.fn.exists = function() { return jQuery(this).length > 0; }

function array_key_exists(array, search) {
    for (var i = 0; i < array.length; i++)
        if (array[i] == search) return true;
    return false;
}
