jQuery(function() {

    // get guids from hidden video divs
    var guids = "";
	
    $("div[class='divVideoId']").each(function() {
        //if (guids.indexOf($(this).text()) == -1)
            guids += ((guids != "") ? "|" : "") + $(this).text();
    });
	
	// attach a rel value to each video trigger to open the correct slide
	jQuery('.video-trigger').each(function(i) {
		jQuery(this).attr('rel',i);
	});
	
	
	
    var jsondata;
    // insert list of GUIDs seperated by | into the guids querystring variable
    if (guids != "") {
        $.getJSON('/services/VideoGuidsToJson.aspx?guids=' + guids, function(data) {
            jsondata = data;
            var idx = 0;
	        jQuery('.simple-modal-trigger').click(function (e) {

		        e.preventDefault();
		        // apply simple modal template
		        if (jQuery('#modalContentArea #simple-modal').length == 0) {
			        jQuery('#modalContentArea').append(jQuery('#modal-simple-template').html());
		        }

		        // modal
		        jQuery('#modalTemplate').modal({
			        opacity: 50,
			        overlayClose: true,
			        zIndex: 2000,
			        onShow: function () { }
		        });
	        });

            jQuery('.video-trigger').live('click',function (e) {
                e.preventDefault();
				
				startingSlide = parseInt(jQuery(this).attr('rel'));
				
                // get an array of requested vid's from the link
				var requested_vids = new Array();
				var vidLength = $('.divVideoId').length;
				if(vidLength == 1 ) {
					try{requested_vids.push('vid' + (1));} catch(e) { console.log("error pushing video"); }
				} else {
					for(var x=1; x<= vidLength; x++) {
						try{requested_vids.push('vid' + (x));} catch(e) { console.log("error pushing videos"); }
					};
				}

                // apply video modal template
                if (jQuery('#modalContentArea #video-modal').length == 0) {
                    jQuery('#modalContentArea').append(jQuery('#modal-video-template').html());
                }

                // modal
                jQuery('#modalTemplate').modal({
                    opacity: 50,
                    overlayClose: true,
                    zIndex: 2000,
                    onShow: function () {

                        // clear out anything in here
                        jQuery('#carouselcols ul').html('');

                        // template and append the vid data	
                        jQuery.each(requested_vids, function (i, v) {
                            if (i == startingSlide) {
                                jsondata[v].autoplay = 'true';
                            } else {
                                jsondata[v].autoplay = 'false';
                            }
                            jsondata[v].id = 'im-video-' + (i + 1);

                            // if we have an iphone, use lores
                            if (DetectSmartphone()) {
                                jsondata[v].ogv = jsondata[v].lores_ogv;
                                jsondata[v].mp4 = jsondata[v].lores_mp4;
                                jsondata[v].webm = jsondata[v].lores_webm;
                                jsondata[v].flv = jsondata[v].lores_flv;
                            } else {
                                jsondata[v].mp4 = jsondata[v].hires_mp4;
                                jsondata[v].ogv = jsondata[v].hires_ogv;
                                jsondata[v].webm = jsondata[v].hires_webm;
                                jsondata[v].flv = jsondata[v].hires_flv;
                            }

                            jQuery('#video-template').tmpl(jsondata[v]).appendTo('#carouselcols ul');
                        });
						
						/* If the links in the video template aren't populated with anything, remove them */
						jQuery('div.video-content','li.column').each(function(i,e) {
							
							jQuery(this).find('.desc > a').each(function() {
								if(jQuery(this).attr('href') == "" && jQuery(this).html().indexOf("View Transcript") > -1 && jQuery(this).html().length <= 18) {
									jQuery(this).hide();
								}
								if(jQuery(this).attr('href') == "" && jQuery(this).html().indexOf("»") > -1 && jQuery(this).html().length <=3) {
									jQuery(this).hide();
								}
								if(jQuery(this).attr('href') == "" && jQuery(this).html()=="") {
									jQuery(this).hide();
								}
								if(jQuery(this).html().indexOf("View Transcript")) {
									jQuery(this).attr('target','_blank');
								}
							});
							
						});

                        // remove the `object` if we have html5 video support
						/* ORIGINAL */
						if(jQuery('body').hasClass('Firefox')) {
							jQuery('.video-js').each(function (i, v) {
								jQuery(this).remove();
							});
						} else {
							jQuery('.video-js').each(function (i, v) {
								if (v.play) {
									jQuery(v).next().remove();
								}
							});
						}
						
						
						// remove the `video` if we have flash video support
						/* NEW */
						/*
                        jQuery('.vjs-flash-fallback').each(function (i, v) {
                        	jQuery(v).next().remove();
                        });
						*/

                        // clear the carousel navigation
                        jQuery('#carousel-navigation').html('');

                        var caroArray = [];
                        // set the carousel navigation
                        jQuery.each(requested_vids, function (i, v) {
                            jQuery('<a/>', {
                                className: (i + 1) + (i == startingSlide ? ' selected' : ''),
                                html: '0' + (i + 1),
                                css: { cursor: 'pointer ' }
                            }).appendTo('#carousel-navigation');
                            caroArray.push("#carousel-navigation ." + (i + 1));
                        });
						
                        jQuery("#carouselcols").jCarouselLite({
                            btnNext: ".next",
                            btnPrev: ".prev",
                            circular: false,
                            visible: 1,
                            scroll: 1,
                            btnGo: caroArray,
							start: startingSlide,
                            afterEnd: function (a) {
                                idx = a.index();
                                jQuery("#carousel-navigation a").removeClass("selected");
                                jQuery("#carousel-navigation a").eq(a.index()).addClass("selected");
                            }
                        });
						
						if(startingSlide == (jQuery("#carouselcols ul li").length-1)) {
							jQuery('.next').hide();
						}
                        // play the first video if the element exists.
						/* ORIGINAL */
						/*
                        if (document.getElementById('im-video-'+startingSlide+1)) {
                            if (document.getElementById('im-video-'+startingSlide+1).play) {
                                document.getElementById('im-video-'+startingSlide+1).play();
                            }
                        }*/

                        // pause the vid when something happens
                        jQuery("#carousel-navigation a,.next, .prev").click(function () {

                            jQuery('.video-js').each(function (i, v) {
                                if (v.pause) {
                                    v.pause();
                                }
                            });

                            jQuery('object').each(function (i, v) {
                                if (v.videoPause) {
                                    v.videoPause();
                                }
                            });

                        });

                        //  hide the previews when you click
                        jQuery(".next,.prev").click(function () {
                            jQuery(".next-preview,.prev-preview").hide();
                        });

                        // next hover
                        jQuery(".next").hover(function () {
                            if (typeof (jsondata[requested_vids[idx + 1]]) !== 'undefined') {
                                jQuery(".next-preview .text").html(jsondata[requested_vids[idx + 1]].thumb_txt);
                                jQuery(".next-preview .number").html('0' + (idx + 2));
                                jQuery(".next-preview img.thumb").attr({ src: jsondata[requested_vids[idx + 1]].thumb_src });
                                jQuery(".next-preview").show();
                            }
                        }, function () {
                            jQuery(".next-preview").hide();
                        });

                        // prev hover
                        jQuery(".prev").hover(function () {
                            if (typeof (jsondata[requested_vids[idx - 1]]) !== 'undefined') {
                                jQuery(".prev-preview .text").html(jsondata[requested_vids[idx - 1]].thumb_txt);
                                jQuery(".prev-preview .number").html('0' + (idx));
                                jQuery(".prev-preview img.thumb").attr({ src: jsondata[requested_vids[idx - 1]].thumb_src });
                                jQuery(".prev-preview").show();
                            }
                        }, function () {
                            jQuery(".prev-preview").hide();
                        });

                        // set up the video when ready
                        VideoJS.setupAllWhenReady();
                    }
                });
            });
        });
    }
});
