var fMozilla	    = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined');
var fSafari		    = navigator.userAgent.toLowerCase().indexOf("safari") != -1;
var fIE			    = !this.fMozilla && !this.fSafari;	// default to IE
var fIE7            = navigator.userAgent.indexOf("MSIE 7.0") != -1;
var fIE6            = (fIE && !fIE7); // Assume IE6 if not 7

// static info dependent on whether we are on the mark or goal page is loaded into this object
var _pageInfo = new Object();

// array of static info for the mark and goal page
var _pageInfoArray =  {            
            "mark":  { xmlpath : "../../Portals/0/competitions/motygotyarmy/mark.xml", roundcookiename : "markRoundCookie", votecookiebasename: "markVoteCookie"},
            "goal": {xmlpath: "../../Portals/0/competitions/motygotyarmy/goal.xml",roundcookiename : "goalRoundCookie", votecookiebasename: "goalVoteCookie"},
            "army": {xmlpath: "../../Portals/0/competitions/motygotyarmy/army.xml",roundcookiename : "armyRoundCookie", votecookiebasename: "armyVoteCookie"}
}

// this xml contains all the info for the marks or goals
var _xmlDoc;

// the current round as specified in the root node of the xml
var _currentRound;

// Max number of rounds to display
var _totalRounds;

// the round the page should currently show
var _roundTab;

var _pageName;
function load(pagename){
    
    _pageInfo = _pageInfoArray[pagename];
    
    _pageName = pagename;
    try
    {
        if(fIE6){
            _xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
            _xmlDoc.async=false;
            _xmlDoc.load(_pageInfo.xmlpath);
            var forms = document.getElementsByTagName("form");
            for(var x = 0; x < forms.length; x++)
            {
                forms.item(x).style.display = "block";
            }
        }
        else{
            var req = new XMLHttpRequest();
            req.open('GET', _pageInfo.xmlpath, false); 
            req.send(null);
            if(req.status == 200){
                var forms = document.getElementsByTagName("form");
                for(var x = 0; x < forms.length; x++)
                {
                    forms.item(x).style.display = "block";
                }
              _xmlDoc = req.responseXML;    
            }
            else{
                alert(req.status);
                alert("Sorry, there was an error loading the xml.");
                return;
            }
        }
    }
    catch(e) {}
    
    try
    {
    parseRoundVariables();
    document.getElementById("A" + _roundTab).style.color = "red";
    document.getElementById("round").value = _currentRound;
    setRoundTdElementStyles();    
    populateCandidates();
    }
    catch(e) {}
}


var _visibleElements =  {            
            "voted":  new Array("vote_1", "vote_2", "vote_3"),
            "notvoted": new Array("vote_1", "vote_2", "vote_3","votesubmit") ,
            "pastround": new Array("votepercent_1","votepercent_2","votepercent_3")
            };

var _hiddenElements =  {            
            "voted":  new Array("votepercent_1","votepercent_2","votepercent_3","votesubmit","chkboxlatestnews","labellatestnews"),
            "notvoted": new Array("votepercent_1","votepercent_2","votepercent_3"),
            "pastround": new Array("vote_1", "vote_2", "vote_3","votesubmit","chkboxlatestnews","labellatestnews")
};

var _enabledElements =  {            
            "voted":  new Array(),
            "notvoted": new Array("vote_1", "vote_2", "vote_3","votesubmit"),
            "pastround": new Array()
};

var _disabledElements =  {            
            "voted":  new Array("vote_1", "vote_2", "vote_3", "votesubmit"),
            "notvoted": new Array(),
            "pastround": new Array("vote_1", "vote_2", "vote_3","votesubmit")
};

function applyAllAttributes(state){
    applyStyleAttributeToList(_visibleElements[state],"display", "inline");
    applyStyleAttributeToList(_hiddenElements[state],"display", "none");
    applyAttributeToList(_enabledElements[state],"disabled",false);
    applyAttributeToList(_disabledElements[state],"disabled",true);
}

function setVoteLabel(state){
    var el = document.getElementById("votelabel");
    if (!el) return; // Never, ever, assume that an element exists.
    if (state =="pastround")
        el.innerHTML ="VOTES";
    else
        el.innerHTML ="VOTE&nbsp;";
}


    function determineRoundClosed(roundCloseDate, roundCloseTime){
        if(!(roundCloseDate) || !(roundCloseTime))
            return false;
            
        var closeDateParts = roundCloseDate.split("/");
        var closeTimeParts = roundCloseTime.split(":");
        
        try{
        var jsCloseDateTime = new Date(parseInt(closeDateParts[2],10), parseInt(closeDateParts[1],10)-1, parseInt(closeDateParts[0],10),parseInt(closeTimeParts[0],10),parseInt(closeTimeParts[1],10));
        }
        catch(err){
            return false;
        }
        var jsCurrentDateTime = new Date();
        
        if (jsCurrentDateTime >= jsCloseDateTime)
            return true;
        else
            return false;
    }
   
    function populateCandidates(){  


        var roundCloseDate;
        var roundCloseTime;
                
        var rounds = _xmlDoc.getElementsByTagName("round");
        var candidates;
        // find the right round node
        for (var r=0;r< rounds.length; r++){
            if(rounds[r].getAttribute("id") == _roundTab){
                roundCloseDate = rounds[r].getAttribute("closedate");
                roundCloseTime = rounds[r].getAttribute("closetime");
                candidates = rounds[r].getElementsByTagName("candidates")[0];                
                break;
            }
        }  

        var state;       
        var existingvote = getCookie(_pageInfo.votecookiebasename + _roundTab); 
        var roundClosed = determineRoundClosed(roundCloseDate, roundCloseTime);
        
        if(_roundTab == _currentRound && !roundClosed){
            state="notvoted";
            /*
            if ((!existingvote) || (_pageName == "army"))
                state = "notvoted";
            else
                state = "voted";
                */
        }
        else if(roundClosed)
        {
            state="pastround";
        }
        else
            state = "notvoted";
            //state ="pastround";             
         
        // if the round tab is the current round, and the user has not yet voted for this round, then enable and display vote elements
        // (radio buttons and submit button)
        applyAllAttributes(state);
        
        if(state == "voted")
           setVote(existingvote);
           
        setVoteLabel(state);
                
       
        //if candidate nodes found, populate the candidate info into the form
        if (candidates){
            for (var c=0; c < candidates.childNodes.length; c++){
               if (candidates.childNodes[c].nodeType ==3)
                    continue;
                var candidateid = candidates.childNodes[c].getAttribute("id");    
                var candidateLabel = document.getElementById("markgoal_" + candidateid);
                var candidateVideo = document.getElementById("markgoalvideo_" + candidateid);
                var candidateVotePercent = document.getElementById("votepercent_" + candidateid);
                
                if(candidateLabel){
                    var cplayername = candidates.childNodes[c].getAttribute("player");
                    var cmatch =candidates.childNodes[c].getAttribute("team");
                    var cdesc = candidates.childNodes[c].getAttribute("desc");
                    candidateLabel.innerHTML = "<b>" + cplayername + "</b> (" + cmatch + ")<br/>" + cdesc;
 
                    var cvotepercentage = candidates.childNodes[c].getAttribute("voting");                   
                    if(state=="pastround"){
                        if (cvotepercentage)
                            candidateVotePercent.innerHTML = "<b>" + cvotepercentage + "</b>";
                        else
                            candidateVotePercent.innerHTML = "<b></b>";
                    }
                    
                }
                if(candidateVideo){
                    var cvideo = candidates.childNodes[c].getAttribute("url");
                    candidateVideo.value = cvideo;
                }
            }
        }
        else{
        // if no data in xml set all candidate info to blank
            for(var i=1;i<=3;i++){
                document.getElementById("markgoal_" + i).innerHTML = "";
                document.getElementById("markgoalvideo_"+ i).value = "";
            }
        }
    }
    
    function applyStyleAttributeToList(list, styleAttrib, value){
        
            for(e=0; e< list.length;e++){
                var elem = document.getElementById(list[e]);
                if (!elem) continue;
                elem.style[styleAttrib] = value;
            }   
    }

    function applyAttributeToList(list, attrib, value){
        
            for(e=0; e< list.length;e++){
                var elem = document.getElementById(list[e]);
                if (!elem) continue;
                elem[attrib] = value;
            }   
    }

    function setRoundTdElementStyles(){
        var table = document.getElementById("RDMenu");
        var listItems =table.getElementsByTagName("TD");
        
        for(var li=0; li< listItems.length; li++){
            
            var tagRoundNum = parseInt(listItems[li].abbr);
            
            if(isNaN(tagRoundNum))
                continue;

            //hide future rounds
            //
            //if(_pageName == "army")
            
            if(_totalRounds >= 0)
            {
                if(tagRoundNum > _totalRounds)
                {
                    listItems[li].style.visibility = "hidden";
                }
                else
                {
                    listItems[li].style.visibility = "visible";
                }
            }
            else
            {
                if (tagRoundNum > _currentRound){
                    listItems[li].style.visibility = "hidden";
                }
                else if(tagRoundNum == _currentRound){
                    listItems[li].style.visibility = "visible";
                }
                else{
                    //do nothing yet
                    listItems[li].style.visibility = "visible";
                }
            }
        }
    }

// parses the currentRound and the roundTab
    function parseRoundVariables(){
        var root = _xmlDoc.documentElement;
        _currentRound = parseInt(root.getAttribute("currentround")); 
        _totalRounds = (parseInt(root.getAttribute("totalrounds")) >= 0 ? parseInt(root.getAttribute("totalrounds")): _currentRound);
        _roundTab = _currentRound;   
    }
    
    function changeRound(round){
        if(_roundTab < 23)
            document.getElementById("A" + _roundTab).style.color = "#00377d";
        else
            document.getElementById("A" + _roundTab).style.color = "#107ecd";
        
        changeRoundVariable(round);
        populateCandidates();
        
        document.getElementById("A" + _roundTab).style.color = "red";
        document.getElementById("round").value = round;
        
        document.getElementById("vote_1").checked = false;
        document.getElementById("vote_2").checked = false;
        document.getElementById("vote_3").checked = false;

    }
    
    function changeRoundVariable(round){
        setCookie(_pageInfo.roundcookiename,round,1);
        _roundTab = round;
    }

//sets cookie to a specified string
    function setCookie(c_name,value,expiredays){
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); 
    }

//gets cookie by cookie name
    function getCookie(c_name)
    {
       if (document.cookie.length>0)
       {
          c_start=document.cookie.indexOf(c_name + "=")
          if (c_start!=-1)
          { 
              c_start=c_start + c_name.length+1;
              c_end=document.cookie.indexOf(";",c_start);
              if (c_end==-1) c_end=document.cookie.length;
              return unescape(document.cookie.substring(c_start,c_end));
          } 
       }
       return "";
    }

    function setVote(value){
          var aOption = document.getElementsByName("vote");
          for (var i = 0; i < aOption.length; i++)
          {
            if (aOption[i].value == value)
              aOption[i].checked = true;
            else
              aOption[i].checked = false;
          }
    }    

    function getVote(){
         var sVote = "";
          var aOption = document.getElementsByName("vote");
          for (var i = 0; i < aOption.length; i++)
          {
            if (aOption[i].checked)
            {
              sVote = aOption[i].value;
              break;
            }
          }
          return sVote;
    }
    
    function latestNewsChecked(){
        //if (_pageName == "army")
        //    return false;
        return false;//document.getElementById("chkboxlatestnews").checked;
    }
    
    function logVote()
    {

        var vote = getVote();
        if (vote == "") 
        {
            //return false; // User did not select a video!
            //User did not select a video to vote for however send them to
            //save.aspx anyway so they can be informed of their mistake
            document.getElementById("failvote").innerHTML = "Please select a video to vote for.";
            return false;
            
        }
        else
        {
            if(latestNewsChecked())
            {
                document.getElementById("latestnews").value = "yes";
            }
            else
            {
                document.getElementById("latestnews").value = "no";
            }
            setCookie(_pageInfo.votecookiebasename + _currentRound,vote,14);  
        }   
    }
    
    function getVideo(videoNum){

        var videoUrl = document.getElementById("markgoalvideo_" + videoNum).value;
        
        //var mediaPlayer = document.getElementById("MediaPlayer");
        
						//alert(oAjaxVideoUrl);
        //var oVideoObject = '<OBJECT id="mediaPlayer" width="486" height="396" classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"><param name="fileName" value="' + videolink + '"><param name="animationatStart" value="true"><param name="transparentatStart" value="true"><param name="autoStart" value="true"><param name="showControls" value="true"><param name="loop" value="true"><EMBED type="application/x-mplayer2" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/" id="mediaPlayer" name="mediaPlayer" displaysize="4" autosize="-1" bgcolor="black" showcontrols="true" showtracker="-1" showdisplay="0" showstatusbar="-1" videoborder3d="-1" width="486" height="396" src="' + videolink + '" autostart="true" designtimesp="5311" loop="true"></EMBED></OBJECT>';
        //var oVideoObject = '<OBJECT id="mediaPlayer" width="486" height="396" classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"><param name="fileName" value="' + videolink + '"><param name="SendPlayStateChangeEvents" value="True"><param name="animationatStart" value="true"><param name="transparentatStart" value="true"><param name="autoStart" value="true"><param name="showControls" value="true"><param name="loop" value="true"><EMBED type="application/x-mplayer2" pluginspage="http://microsoft.com/windows/mediaplayer/en/download/" id="mediaPlayer" name="mediaPlayer" displaysize="4" autosize="-1" bgcolor="black" showcontrols="true" showtracker="-1" showdisplay="0" showstatusbar="-1" videoborder3d="-1" width="486" height="396" src="' + videolink + '" autostart="true" designtimesp="5311" loop="true"></EMBED></OBJECT>';
    	if(document.getElementById("video_object").innerHTML.length < 50)
    	{
    	    var oVideoObject = '<OBJECT id="MediaPlayer1" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" width="486" height="396" type="application/x-oleobject"><param name="FileName" value="' + videoUrl + '"/><param name="AutoStart" value="True" /><embed type="application/x-ms-wmp" width="486" height="396" src="' + videoUrl + '"></embed></OBJECT>';
            document.getElementById("video_object").innerHTML = oVideoObject;
            
                    document.getElementById('video_object').style.display = "block";
        document.getElementById('video_sponsor').style.display = "none";
        }
        else
        {
            //When a better method is found for changing the video place it here
	        document.getElementById('video_object').style.display = "none";
            document.getElementById('video_sponsor').style.display = "block";
        
    	    var oVideoObject = '<OBJECT id="MediaPlayer1" classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95" width="486" height="396" type="application/x-oleobject"><param name="FileName" value="' + videoUrl + '"/><param name="AutoStart" value="True" /><embed type="application/x-ms-wmp" width="486" height="396" src="' + videoUrl + '"></embed></OBJECT>';
            document.getElementById("video_object").innerHTML = oVideoObject;
            
            document.getElementById('video_object').style.display = "inline";
            document.getElementById('video_sponsor').style.display = "none";
            //videoUrl
        }

                                            
        //document.MediaPlayer.FileName = videolink;
        //document.mediaPlayer.SetFileName(videolink);
        
        //AC_AX_RunContent( 'id','MediaPlayer','width','320','height','240','classid','CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95','standby','Loading Windows Media Player components...','type','application/x-oleobject','src',videolink,'name','MediaPlayer','showcontrols','true','showstatusbar','false','showdisplay','false','autostart','true','filename',videolink ); 
        /*
        var videoFileParam = document.getElementById("videoFileParam");
        videoFileParam.value = videolink;
        var videoEmbed = document.getElementById("videoEmbed");
        */

    }
    
    /*
    function motyLinkOver(el){
        el.className = 'motylinkover';
    }
    function motyLinkChosen(el){
        el.className = 'motylinkchosen';
    }
    
    function motyLinkUnchosen(el){
        el.className = 'motylinkunchosen';    
    }
    function changeEvent(el, msg, fnc)
    {
        detachEvent(el,msg,fnc);
        attachEvent(el,msg,fnc);
    }
    function attachEvent(el, msg, fnc)
    {
        if (fIE)
            el.attachEvent(msg, fnc);
        else
        {
            // Remove 'on'
            el.addEventListener(msg.substr(2), fnc, false);
        }
    };

    function detachEvent(el, msg, fnc)
    {
        if (fIE)
            el.detachEvent(msg, fnc);
        else
        {
            // Remove 'on'
            el.removeEventListener(msg.substr(2), fnc, false);
        }
    };
    */