var control;
var volMoving, progressMoving, dragState;
var timer;
var currentMovie = 0;
var movieRoot = "http://www.internetgolfacademy.com/SwingStore/";
var playlist = new Array(), titles = new Array();
var clickCount = 0;
var adRaiseTime = 5, adLength = 5, adRepeatFreq = 30;
var instrRaiseTime = 1, instrLength = 6;
var adURL = "http://www.v1golfacademy.com/v1home.asp";

function changeSource( videoSource ) {
	// start timer to watch the thumb
	if( timer == null ) {
	    updateProgress();
	}
	
	playlist = new Array();
	    
	// if source is .wvx
	var len = videoSource.length;
	if( videoSource.charAt(len-3) == 'w' &&
	    videoSource.charAt(len-2) == 'v' &&
	    videoSource.charAt(len-1) == 'x' ) {
	    // populate playlist
	    createPlaylist( videoSource );
	    //testPlaylist();
	} else {
	    playlist[0] = videoSource;
	    titles[0] = "Your V1 lesson";
	}
	
	currentMovie = 0;
    loadMovie();
}

function loadMovie() {
	var media = control.content.findName("featureMedia");

	media.stop();
    media.source = playlist[currentMovie];
	control.content.findName("featureFadeIn").begin();
	
	// clear overlays
    var anim = control.content.findName("adLower");
    anim.begin();
    anim.seek(anim.Duration);
    var anim = control.content.findName("hideInstructorInfo");
    anim.begin();
    anim.seek(anim.Duration);

    // fix next/prev buttons
	if( currentMovie == 0 ) {
	    control.content.findName("prevButton").opacity = ".1";
	} else {
	    control.content.findName("prevButton").opacity = "1";
	}
	
	if( currentMovie == playlist.length - 1 ) {
	    control.content.findName("nextButton").opacity = ".1";
	} else {
	    control.content.findName("nextButton").opacity = "1";
	}
}

function createPlaylist( source ) {  
    var xmlhttp;
    if( window.XMLHttpRequest ) {
        // non-IE
        xmlhttp = new XMLHttpRequest();
    } else if( window.ActiveXObject ) {
        // IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } else {
        // TODO - ERROR
        alert("XML HTTP Request not created");
    }
    xmlhttp.open( "GET", source, 0 );
    xmlhttp.send("");
    
    var strProgramPath = xmlhttp.responseText;
    // STRIP OUT AMPERSANDS
    strProgramPath = strProgramPath.replace("&","");
    var objXML;
    if( document.implementation && document.implementation.createDocument ) {
        // non-IE
        var parser = new DOMParser();
        objXML = parser.parseFromString(strProgramPath,"text/xml");
    } else if( window.ActiveXObject ) {
        objXML = new ActiveXObject("Microsoft.XMLDOM");
        objXML.async = false;
        objXML.loadXML(strProgramPath);
    } else {
        // TODO ERROR
        alert("XML Response not read");
    }
    
    // get all REF elements
    var objLst = objXML.getElementsByTagName("REF")
    // get all titles
    var titleLst = objXML.getElementsByTagName("TITLE")
    
    var i = 0;
    for( i = 0; i < objLst.length; i++ ) {
        titles[i] = "" + titleLst.item(i+1).childNodes[0].nodeValue;
        playlist[i] = "" + movieRoot + "" + objLst.item(i).getAttribute("HREF");
    }
    
    objXML = null;
    xmlhttp = null;
}

/*function testPlaylist() {
    var media = control.content.findName("featureMedia");
    
    media.removeEventListener("mediaOpened", "media_start");
    media.addEventListener("mediaOpened", "testPlaylist2");
    media.source = playlist[0];
}

function testPlaylist2() {
    if( currentMovie == playlist.length-1 ) {
        // successfully reached last movie
        alert("fin");
        //media.removeEventListener("mediaOpened", "testPlaylist2");
        //media.addEventListener("mediaOpened", "media_start");
        return;
    } else {
        // try next movie
        alert("pass:" + playlist[currentMovie]);
        media_next();
    }
}*/

function progressDragStart( sender ) {
	var media = control.content.findName("featureMedia");

	// pause if necessary
	dragState = media.currentState;
	if( dragState == "Playing" ) {
		media.pause();
	}

	progressMoving = true;
	sender.captureMouse();
}

function progressDragStop( sender ) {
	var media = control.content.findName("featureMedia");

	// resume state
	if( dragState === "Playing" ) {
		media.play();
	}

	progressMoving = false;
	sender.releaseMouseCapture();
}

function progressDragMove( sender, mouseEventArgs ) {
	var slider = control.content.findName("progressSlider");
	var thumb = control.content.findName("progressThumb");
	var media = control.content.findName("featureMedia");

	if( progressMoving ) {
		var position = mouseEventArgs.getPosition(slider).x / slider.width * media.naturalDuration.seconds;
        changePosition( position );
		updateThumb( position );
	}
}

function progressClick( sender, mouseEventArgs ) {
	var media = control.content.findName("featureMedia");
	var slider = control.content.findName("progressSlider");
    
    var pos = mouseEventArgs.getPosition(slider).x / slider.width * media.naturalDuration.seconds;
    changePosition( pos );
    updateThumb( pos );
}

function changePosition( seconds ) {
	var media = control.content.findName("featureMedia");
	var position = media.position;
	position.seconds = seconds;
	
	if( position.seconds < 0 ) {
	    position.seconds = 0;
	} else if( position.seconds > media.naturalDuration.seconds ) {
	    position.seconds = media.naturalDuration.seconds;
	}
	
	media.position = position;
}

function updateThumb( currentPos ) {
	var slider = control.content.findName("progressSlider");
	var thumb = control.content.findName("progressThumb");
	var media = control.content.findName("featureMedia");

	if( currentPos < 0 ) {
		currentPos = 0;
	} else if( currentPos > media.naturalDuration.seconds ) {
		currentPos = media.naturalDuration.seconds;
	}

	var len = media.naturalDuration.seconds;
	var pos = currentPos/len * slider.width + slider["Canvas.Left"];
	if( media.currentState == "Playing" || media.currentState == "Stopped" || media.currentState == "Paused" ) {
        thumb["Canvas.Left"] = pos - thumb.width/2;
    }
}

function updateProgress() {
	var media = control.content.findName("featureMedia");
	updateThumb( media.position.seconds );
	
	// update time markers
	var currentMinute = Math.floor(media.position.seconds/60);
	var currentSecond = Math.floor(media.position.seconds - 60*currentMinute);
	if( currentSecond < 10 ) {
	    currentSecond = "0" + currentSecond;
	}
	control.content.findName("timeElapsed").text = currentMinute + ":" + currentSecond;
	
	currentMinute = Math.floor((media.naturalDuration.seconds-media.position.seconds)/60);
	currentSecond = Math.floor((media.naturalDuration.seconds-media.position.seconds) - 60*currentMinute);
	if( currentSecond < 10 ) {
	    currentSecond = "0" + currentSecond;
	}
	control.content.findName("timeRemaining").text = currentMinute + ":" + currentSecond;
	
    // if feature movie
    if( titles[currentMovie] == "Your V1 lesson" ) {
	    var pos = media.position.seconds;
        var watermark = control.content.findName("watermark");
        var ad = control.content.findName("adRect");
        var instrPicture = control.content.findName("instructorPicture");
        var instrName = control.content.findName("instructorName");
	    
	    // check if ad is raised
	    var i = 0;
	    for( i = 0; i < media.markers.count; i++ ) {
	        if( media.markers.getItem(i).time.seconds > pos ) {
	            break;
	        }
	    }
	    i--;
	    for( j = i; j >= 0; j-- ) {
	        if( media.markers.getItem(j).type == "showAd" ) {
	            var anim = control.content.findName("adRaise");
	            if( media.position.seconds > media.markers.getItem(j).time.seconds + anim.duration.seconds ) {
	                // bring ad up
	                anim.begin();
	                anim.seek(anim.Duration);
	            }
	            break;
	        } else if( media.markers.getItem(j).type == "hideAd" || j == 0 ) {
	            // lower ad
	            var anim = control.content.findName("adLower");
	            if( media.position.seconds > media.markers.getItem(j).time.seconds + anim.duration.seconds ) {
	                anim.begin();
	                anim.seek(anim.Duration);
	            }
	            break;
	        }
	    }
	    
	    // check that instructor info is up
	    var upAnim = control.content.findName("showInstructorInfo");
	    var downAnim = control.content.findName("hideInstructorInfo");
	    if( pos > (instrRaiseTime+upAnim.Duration.seconds) && pos < (instrRaiseTime+instrLength) ) {
	        upAnim.begin();
	        upAnim.seek(upAnim.Duration);
	    } else if( pos < instrRaiseTime || pos > instrRaiseTime+instrLength+downAnim.Duration.seconds) {
	        downAnim.begin();
	        downAnim.seek(downAnim.Duration);
	    }
	} else {
        var anim = control.content.findName("adLower");
        anim.begin();
	    anim.seek(anim.Duration);
        
        var anim = control.content.findName("hideInstructorInfo");
        anim.begin();
        anim.seek(anim.Duration);
    }
	    
	
	timer = setTimeout( "updateProgress()", 100 );
}

function markerReached( sender, markerEventArgs ) {
    // if feature movie
    if( titles[currentMovie] == "Your V1 lesson" ) {
        if( markerEventArgs.marker.type == "showAd" ) {
            control.content.findName("adRaise").begin();
        } else if( markerEventArgs.marker.type == "hideAd" ) {
            control.content.findName("adLower").begin();
        } else if( markerEventArgs.marker.type == "showInstr" ) {
            control.content.findName("showInstructorInfo").begin();
        } else if( markerEventArgs.marker.type == "hideInstr" ) {
            control.content.findName("hideInstructorInfo").begin();
        }
    }
}

function media_start() {
    // set markers
    var media = control.content.findName("featureMedia");
    for( i = 0; i < media.naturalDuration.seconds; i+=adRepeatFreq ) {
        var startTime = adRaiseTime + i;
        var endTime = adRaiseTime + i + adLength;
        var beginMarker = control.content.createFromXaml( '<TimelineMarker Time="0:' + Math.floor(startTime/60) + ':' + (startTime-Math.floor(startTime/60)*60) + '" Type="showAd" Text=""/>' );
        var endMarker = control.content.createFromXaml( '<TimelineMarker Time="0:' + Math.floor(endTime/60) + ':' + (endTime-Math.floor(endTime/60)*60) + '" Type="hideAd" Text=""/>' );
        media.markers.add(beginMarker);
        media.markers.add(endMarker);
    }
    
    beginMarker = control.content.createFromXaml( '<TimelineMarker Time="0:0:' + instrRaiseTime + '" Type="showInstr" Text=""/>' );
    endMarker = control.content.createFromXaml( '<TimelineMarker Time="0:0:' + (instrRaiseTime+instrLength) + '" Type="hideInstr" Text=""/>' );
    media.markers.add(beginMarker);
    media.markers.add(endMarker);
    
    updateInstructorInfo();

    if( control.content.findName("playButton").opacity == 1 ) {
        media_playPause();
    } else {
        var media = control.content.findName("featureMedia");
        media.play();
    }
}

function media_click( sender, mouseEventArgs ) {
    // toggle fullscreen on double click
    // play/pause on single click
    if( clickCount >= 1 ) {
        control.content.fullScreen = !control.content.fullScreen;
        clickCount = 0;
    } else {
        media_playPause();
        clickCount++;
        setTimeout( "clickCount = 0;", 500 );
    }
}

function media_playPause() {
	var media = control.content.findName("featureMedia");

	if( media.currentState != "Playing" ) {
		control.content.findName("playToPause").begin();
		media.play();
		
		// resume animations
		control.content.findName("adRaise").resume();
		control.content.findName("adLower").resume();
		control.content.findName("showInstructorInfo").resume();
		control.content.findName("hideInstructorInfo").resume();
	} else {
		control.content.findName("pauseToPlay").begin();
		media.pause();
		
		// pause animations
		control.content.findName("adRaise").pause();
		control.content.findName("adLower").pause();
		control.content.findName("showInstructorInfo").pause();
		control.content.findName("hideInstructorInfo").pause();
	}
}

function media_end() {
    if( currentMovie < playlist.length - 1 ) {
        currentMovie++;
        loadMovie();
    } else {
	    control.content.findName("pauseToPlay").begin();
    	
	    media_stop();
	}
}

function media_stop() {
	var media = control.content.findName("featureMedia");

	if( media.currentState == "Playing" ) {
		control.content.findName("pauseToPlay").begin();
	}
	
	// set thumb to left
	updateThumb(0);

	media.stop();
}

function media_prev() {
    currentMovie--;
    if( currentMovie < 0 ) {
        currentMovie = 0;
    } else {
        loadMovie();
    }
}

function media_next() {
    currentMovie++;
    if( currentMovie > playlist.length-1 ) {
        currentMovie = playlist.length-1;
    } else {
        loadMovie();
    }
}

function adClicked() { 
    // pause
    if( control.content.findName("featureMedia").currentState == "Paused" ) {
        media_playPause();
    }
    // open in new win
    window.open( adURL );
}

function volumeDown() {
	setVolume( getVolume() - .1 );
}

function volumeUp() {
	setVolume( getVolume() + .1 );
}

function volDragStart( sender ) {
	volMoving = true;
	sender.captureMouse();
}

function volDragStop( sender ) {
	volMoving = false;
	sender.releaseMouseCapture();
}

function volDragMove( sender, mouseEventArgs ) {
	var slider = control.content.findName("volSlider");
	var thumb = control.content.findName("volThumb");
	var media = control.content.findName("featureMedia");

	if( volMoving ) {
		setVolume( mouseEventArgs.getPosition(slider).x / slider.width );
	}
}

function volClick( sender, mouseEventArgs ) {
	var slider = control.content.findName("volSlider");
	
    setVolume( mouseEventArgs.getPosition(slider).x / slider.width );
}

function getVolume() {
	var media = control.content.findName("featureMedia");

	return media.volume;
}

function setVolume( level ) {
	var slider = control.content.findName("volSlider");
	var thumb = control.content.findName("volThumb");
	var media = control.content.findName("featureMedia");

	if( level > 1 ) {
		level = 1;
	} else if( level < 0 ) {
		level = 0;
	}

	pos = level * slider.width + slider["Canvas.Left"];
	thumb["Canvas.Left"] = pos - thumb.width/2;
	media.volume = level;
}

function mute() {
	var media = control.content.findName("featureMedia");

	if( media.isMuted == true ) {
		control.content.findName("unMuteAnimation").begin();
		media.isMuted = false;
	} else {
		control.content.findName("muteAnimation").begin();
		media.isMuted = true;
	}
}

function featureFailed() {
	var media = control.content.findName("featureMedia");
	
	//load in WMP
	//window.open( media.source, "" );
	window.open( source, "" );
	//window.close();
	//setTimeout("window.close();",500);
}

function onFullScreenChange() {
    scaleLayout();
    media_playPause();
}

function onResize() {
    scaleLayout();
}

function scaleLayout() {    
    var width = control.content.actualWidth;
    var height = control.content.actualHeight;
    var root = control.content.root;
    var scaleX, scaleY, scale;
    
    scaleX = width/root.width;
    scaleY = height/root.height;
    scale = Math.min( scaleX, scaleY );
    
    root["Canvas.Left"] = (width - root.width*scale)/2;
    
    control.content.findName("stretchTransform").scaleX = scale;
    control.content.findName("stretchTransform").scaleY = scale;
}

function highlightButton( sender ) {
    if( sender.opacity == "1" ) {
        var anim = control.content.findName("buttonFadeIn");
        anim.stop();
        
        anim["Storyboard.TargetName"] = sender.name + "Fill";
        
        anim.begin();                        
    }
}

function unHighlightButton( sender ) {
    if( sender.opacity == "1" ) {
        var anim = control.content.findName("buttonFadeOut");
        anim.stop();
        
        anim["Storyboard.TargetName"] = sender.name + "Fill";
        
        anim.begin();
    }
}