var qArray = new Array();
var hArray = new Array();
var sArray = new Array();
//link
var lArray = new Array();
//image
var iArray = new Array();
//title
var tArray = new Array();
//content
var cArray = new Array();

//caption
var caArray = new Array();

//name
var nArray = new Array();
//selected image
var siArray = new Array();
//over image
var oArray = new Array();

var popupDir = '/_layouts/1033/styles/plantemoran/2011_design/images/popup/';
var basePath = '/_layouts/1033/styles/plantemoran/2011_design/';
var altImgArray = new Array();
var altLinkArray = new Array();

var colorArray = new Array();
var hPosArray = new Array();
var sPosArray = new Array();

var heightArray = new Array();

var headPosRef = 300;

var subPosRef = new Array();
subPosRef["bottom"] = 310;
subPosRef["top"] = 270; //263;

var index = 0;
var interval;
var time = 6000;

var altIndex = 0;
var altInterval;
var altTime = 7000;
var slideshow;
var dir = "f";

// loads normal type slideshow
function loadService(view, list, site, type) {
    var slideshow = type;
    jQuery().SPServices({
        operation: "GetListItems",
        web_url: site,
        async: false,
        listName: list,
        viewName: '',
        //  CAMLViewFields: '<ViewFields><FieldRef Name="Title"/></ViewFields>',

        completefunc: function(xData, Status) {
            //alert(xData.responseXML.toString());
            jQuery(xData.responseXML).find("[nodeName='z:row']").each(function() {
                //var liHtml = jQuery(this).attr('ows_Title');


                // var description = jQuery(this).find('description').text();
                var image = "/" + jQuery(this).attr('ows_RequiredField');
                var title = jQuery(this).attr('ows_Title');
                var content = jQuery(this).attr('ows_Content');

                if (!content) {
                    //try lower case
                    content = jQuery(this).attr('ows_content');
                }
                var caption = jQuery(this).attr('ows_Caption');

                var linkURL = jQuery(this).attr('ows_Link');
                var name = '';
                var sel_image = '';


                lArray.push(linkURL);
                iArray.push(image);
                tArray.push(title);
                cArray.push(content);
                caArray.push(caption);





            });
        }
    });

    if (slideshow == "home") {
        createSlideshow();
    } else if (slideshow == "inner") {
        createInnerSlideshow();
    } else if (slideshow == "team") {
        createTeamSlideshow();
    }

}

function loadTeamSlides(team, data) {
    slideshow = 'team';

    //set the active alpha letters
    //alert(data.responseXML.xml);
    jQuery(data.responseXML).find("[nodeName='z:row']").each(function() 
{

//alert('LinkFileName ' + jQuery(this).attr('ows_LinkFilename'));
//alert ('Full Image' + jQuery(this).attr('ows_Full_Image'));
//alert('Image BG' + jQuery(this).attr('ows_Image_BG'));
//alert('Full Image Over ' + jQuery(this).attr('ows_Full_Image_Over'));
//alert('Position ' + jQuery(this).attr('ows_Position'));
//alert('Title ' + jQuery(this).attr('ows_Title'));
//alert('Content ' + jQuery(this).attr('ows_Content'));
//alert('Quote ' + jQuery(this).attr('ows_Quote'));
//alert('Extra Content ' + jQuery(this).attr('ows_HRBody1'));

        //big check to make sure the fields we want are populated, if any are missing, skip this row

        //if (jQuery(this).attr('ows_LinkFilename') != '' && jQuery(this).attr('ows_Full_Image') != '' && jQuery(this).attr('ows_Image_BG') != '' && jQuery(this).attr('ows_Full_Image_Over') != ''        && jQuery(this).attr('ows_Position') != '' && jQuery(this).attr('ows_Title') != '' && jQuery(this).attr('ows_Content') != '' && jQuery(this).attr('ows_Quote') != '')

     if (jQuery(this).attr('ows_LinkFilename') != '' && !!jQuery(this).attr('ows_Full_Image') && !!jQuery(this).attr('ows_Image_BG') && !!jQuery(this).attr('ows_Full_Image_Over') 
        && jQuery(this).attr('ows_Position') != '' && jQuery(this).attr('ows_Title') != '' && jQuery(this).attr('ows_Content') != '' && jQuery(this).attr('ows_Quote') != '')
  {
		//alert('GoodRow: LinkFileName ' + jQuery(this).attr('ows_LinkFilename'));

            var name = '';
            var title = jQuery(this).attr('ows_LinkFilename');

            if (title != '' && title.indexOf('-') > -1) {

                //get last name using the format first_last
                var name = title.split('-');
                //console.log(name[1]);

                if (name[1] != '') {
                    //id to activate
                    var id = '#alpha_' + name[1].charAt(0).toUpperCase();
                    //alert(id);
                    jQuery(id).addClass('populated');
                }



//alert('CheckPoint 1');
                //build slideshow array
//alert ('Full Image' + jQuery(this).attr('ows_Full_Image'));

if (jQuery(this).attr('ows_Full_Image') !='')
{
//alert ('IF the image is undefined then this will not capture!');
}

if (!jQuery(this).attr('ows_Full_Image'))
{
//alert ('Image is UNDEFINED');
}

                var image = jQuery(this).attr('ows_Full_Image');

		//alert ('Full Image: ' + image);
                //console.log(image);
                if (image.indexOf(',') > -1) {
                    image = image.split(',');
                    image = image[0];
                }

//alert('CheckPoint 2');


                // var over = jQuery(this).attr('ows_Full_Image_Over').split(',');
                var selected = jQuery(this).attr('ows_Image_BG');
                if (selected.indexOf(',') > -1) {
                    selected = selected.split(',');
                    selected = selected[0];
                }

//alert('CheckPoint 3');

                var name = jQuery(this).attr('ows_Position');
                title = jQuery(this).attr('ows_Title');
                var content = jQuery(this).attr('ows_Content');

                if (!content) {
                    //try lower case
                    content = jQuery(this).attr('ows_content');
                }

                var caption = jQuery(this).attr('ows_CresaQuote');

//alert('CheckPoint 4');

                //var order = parseInt(jQuery(this).attr('ows_Order'));

                iArray.push(image);
                tArray.push(title);
                cArray.push(content);
                caArray.push(caption);
                nArray.push(name);
                siArray.push(selected);
                // oArray.push(over[0]);
//alert('CheckPoint 5');

            }
        }

    });

    createTeamSlideshow();


    jQuery('.populated').click(function() {

        var id = jQuery.trim(jQuery(this).html().toLowerCase());
        //var team = 'healthcare';


        var wherePop = "";
        if (team != '') {
            wherePop = "<Query><Where><And><Contains><FieldRef Name='Team_Association'/><Value Type='text'>" + team + "</Value></Contains><Contains><FieldRef Name='FileLeafRef'/><Value Type='text'>-" + id + "</Value></Contains></And></Where></Query>";
        } else {
            wherePop = "<Query><Where><Contains><FieldRef Name='FileLeafRef'/><Value Type='text'>-" + id + "</Value></Contains></Where></Query>";

        }


        //clear out old data
        jQuery('#members').children().remove();

        jQuery().SPServices.defaults.webURL = 'http://www.pmcresa.com/pmcresa/about/Team/';
        				      
//alert ('start1d');
	jQuery().SPServices({
            operation: "GetListItems",
            async: false,
            listName: 'Pages',
            viewName: '',
            CAMLQuery: wherePop,
            completefunc: setPopulated
        });

//alert ('end1');
    });


}


function setPopulated(data, status, request) {
    //set the active alpha letters
 
 jQuery(data.responseXML).find("[nodeName='z:row']").each(function(index) {

        var title = jQuery(this).attr('ows_LinkFilename');

	// we didnt use 'title' in prod to contain the name. Use position field instead. Means we have to update the name capture area as well.
        //var name = jQuery(this).attr('ows_Title');

	var name = jQuery(this).attr('ows_Position');

//alert('Image BG' + jQuery(this).attr('ows_Image_BG'));

// Need to have this check here otherwise routine will err. Some list items not used and will have null pics. Skip those!
	if (!!jQuery(this).attr('ows_Image_BG')) 
	{
        	var bg_image = jQuery(this).attr('ows_Image_BG').split(',');

	        //create the pop up box
        	var selectedBox = '<div id="selected_member_' + index + '" class="selected_slide"><div class="selected_inner"><div class="topBox" style="background-image:url(' + bg_image[0] + ');"><div class="textBox"><div class="name">' + name + '</div><div class="position">' + jQuery(this).attr('ows_Title') + '</div><div class="quote">' + jQuery(this).attr('ows_CresaQuote') + '</div></div></div><div class="content">' + jQuery(this).attr('ows_Content') + '</div></div></div>';

	        jQuery('#members').append('<li href="#selected_member_' + index + '">' + name + ' ' + selectedBox + '</li>');
	}
    });

    jQuery('#members').children().each(function() {
        jQuery(this).fancyZoom({ directory: popupDir });
   });


}



//not used anymore	
function handleXML(data, status, request) {

    slideshow = "home";

    jQuery(data).find('item').each(function() {

        var description = jQuery(this).find('description').text();
        var image = jQuery(this).find('link').text();
        var title = ''; //jQuery(this).find('title').text();
        var content = ''; //jQuery(this).find('content').text();
        var caption = ''; //jQuery(this).find('caption').text();
        var linkURL = '';
        var name = '';
        var sel_image = '';
        var active = '';
        var order = '';

        description = description.replace(/<div><b>/g, '').replace(/<\/b>/g, '');
        var arrInnerDescription = description.split('</div>');

        for (var x = 0; x < arrInnerDescription.length - 1; x++) {
            var arrValue = arrInnerDescription[x].split(': ');
            var key = arrValue[0].toLowerCase().replace(/^\s+|\s+$/g, '');

            switch (key) {
                case "content": content = arrValue[1]; break;
                case "caption": caption = arrValue[1]; break;
                case "title": title = arrValue[1]; break;
                case "link": linkURL = arrValue[1]; break;
                case "active": active = arrValue[1]; break;
                case "order": order = arrValue[1]; break;
            }
        }


        if (active == 'Yes') {

            //team slide data
            // var name = jQuery(this).find('name').text();
            // var sel_image = jQuery(this).find('selected_image').text();

            var index = order - 1;
            lArray[index] = linkURL;
            iArray[index] = image;
            tArray[index] = title;
            cArray[index] = content;
            caArray[index] = caption;

            nArray[index] = name;
            siArray[index] = sel_image;

            /*
            lArray.push(linkURL);
            iArray.push(image);
            tArray.push(title);
            cArray.push(content);
            caArray.push(caption);

	        nArray.push(name);
            siArray.push(sel_image);*/

        }


    });
    slideshow = jQuery(data).find('channel').find('description:first').text();


    /* not used
    jQuery(data).find('img').each(function(){
    altImgArray.push(jQuery(this).attr("src"));
    altLinkArray.push(jQuery(this).attr("href"));
    slideshow = "alt";
    }); */


    if (slideshow == "home") {
        createSlideshow();
    } else if (slideshow == "inner") {
        createInnerSlideshow();
    } else if (slideshow == "team") {
        createTeamSlideshow();
        //}else if(slideshow == "alt"){
        //	createAltSlideshow();	
    }


}

function swapSlide() {
    
//alert('in function swapSlide!');
//alert(slideshow);
    //$(".debug").text(dir);
    //

    var startIndex = index;




    if (slideshow == 'team') {


        if (index == 0 && dir == "b") {
            index = iArray.length - 1;
        } else if (index == iArray.length - 1 && dir == "f") {
            index = 0;

        } else if (dir == "f") {

            index++;
        } else {
            index--;

        }
        if (index == iArray.length - 1) {
            jQuery(".rightArrow").hide();
        } else {
            jQuery(".rightArrow").show();
        }

        if (startIndex - 5 == 0) {
            jQuery(".leftArrow").hide();
        } else {
            jQuery(".leftArrow").show();
        }

        if (dir == 'b') {

            //move last slides over
            var lastSlide = startIndex;
            jQuery("#slide-" + (startIndex - 5)).show();



            for (var i = startIndex - 5; i < iArray.length; i++) {
                var p = parseInt(i - 1);
                var prev_pos = jQuery("#slide-" + i).css('left');

                var left = parseInt(prev_pos) + jQuery("#slide-" + p).width();
                if (i == 0) {
                    left = 0;
                }
                var $out = jQuery("#slide-" + i);
                //console.log(i + " " + prev_pos + " " + parseInt(jQuery("#slide-"+i).width()) +" "+ left);
                $out.animate({
                    left: left
                }, 500,
				 function() {

				 });

            }


            //then move in the rest


        } else {

            jQuery("#slide-" + index).show();

            jQuery(".leftArrow").show();

            var firstSlide = index - 5;
            //move 1st slide somewhere to the left

            var $out = jQuery("#slide-" + firstSlide);
            $out.animate({
                left: -$out.outerWidth()
            }, 500,
			 function() {
			     jQuery(this).hide();
			     jQuery(this).css('left', -jQuery(this).outerWidth());



			 });

            //move next slides over
            for (var i = firstSlide + 1; i < iArray.length; i++) {
                var p = parseInt(i - 1);
                var prev_pos = jQuery("#slide-" + p).css('left');

                var left = parseInt(prev_pos);
                if (i == firstSlide + 1) {
                    left = 0;
                }

                var $out = jQuery("#slide-" + i);

                $out.animate({
                    left: left
                }, 500,
				 function() {

				 });

            }


        }

    } else {
        if (index == 0 && dir == "b") {
            index = iArray.length - 1;
        } else if (index == iArray.length - 1 && dir == "f") {
            index = 0;

        } else if (dir == "f") {

            index++;
        } else {
            index--;

        }

        jQuery("#slide-" + index).show();

        jQuery("#slide-" + index).css('left', jQuery("#slide-" + index).outerWidth());


        if (dir == 'b') {
            jQuery("#slide-" + index).css('left', -jQuery("#slide-" + index).outerWidth());

            var $out = jQuery("#slide-" + startIndex);
            $out.animate({
                left: $out.outerWidth()
            }, 1000,
			 function() {
			     jQuery(this).hide();
			     jQuery(this).css('left', jQuery(this).outerWidth());

			 });

        } else {
            var $out = jQuery("#slide-" + startIndex);
            $out.animate({
                left: -$out.outerWidth()
            }, 1000,
			 function() {
			     jQuery(this).hide();
			     jQuery(this).css('left', jQuery(this).outerWidth());

			 });
        }

        var $in = jQuery("#slide-" + index);
        $in.animate({
            left: 0
        }, 1000);

        //$(".debug").append(index);

        //jQuery("#slide-"+index).fadeIn(500);


        jQuery(".slideshowContainer .overlay .link a").attr('href', lArray[index]);
        jQuery(".slideshowContainer .overlay .title").html(tArray[index]);
        jQuery(".slideshowContainer .overlay .content").html(cArray[index]);
        jQuery(".slideshowContainer .caption span").html(caArray[index]);

        dir = "f";

    }

}

function swapAltSlide() {
    //alert("test");

    jQuery("#image-" + altIndex).hide();

    if (altIndex == altImgArray.length - 1) {
        altIndex = 0;
    } else {
        altIndex++;
    }

    jQuery("#image-" + altIndex).fadeIn(500);

    jQuery("#image-" + altIndex + " .headline").hide().delay(800).fadeIn(500);
    jQuery("#image-" + altIndex + " .sub").css({ marginLeft: "300px", opacity: 0 }).delay(800).animate({ marginLeft: "46px", opacity: 100 }, 500, 'swing');
}

function startAltSlideshow() {
    clearInterval(altInterval);
    altInterval = setInterval(swapAltSlide, altTime);
}

function stopAltSlideshow() {
    clearInterval(altInterval);
}

function createAltSlideshow() {
    for (var i = altImgArray.length - 1; i >= 0; i--) {

        jQuery(".altSlideshow").append('<div id="image-' + i + '" class="image"></div>');
        jQuery(".altSlideshow #image-" + i).append('<a href="' + altLinkArray[i] + '"><img src="' + altImgArray[i] + '" border="0" alt="" /></a>');

        if (i > 0) { jQuery(".altSlideshow #image-" + i).hide(); }
    }

    startAltSlideshow()
}

function createSlideshow() {

    for (var i = iArray.length - 1; i >= 0; i--) {

        jQuery(".slideshow").append('<div id="slide-' + i + '" class="slide" style="background-image:url(\'' + iArray[i] + '\');"></div>')


        var theLink = lArray[i];
        jQuery(".slideshowContainer .overlay .link a").attr('href', lArray[index]);
        jQuery(".slideshowContainer .overlay .title").html(tArray[index]);
        jQuery(".slideshowContainer .overlay .content").html(cArray[index]);
        jQuery(".slideshowContainer .caption span").html(caArray[index]);

        jQuery(".slideshowContainer #slide-" + i).click(gotoLink); //

        if (i > 0) { jQuery(".slideshowContainer #slide-" + i).hide(); }

    }
    jQuery(".slideshowContainer .overlay").show();
    jQuery(".rightArrow").show();
    jQuery(".leftArrow").show();
    resetInterval()
}


function createInnerSlideshow() {

    for (var i = iArray.length - 1; i >= 0; i--) {

        jQuery(".slideshow").append('<div id="slide-' + i + '" class="slide" style="background-image:url(\'' + iArray[i] + '\');"></div>')



        //hide overlay content not populated

        if (cArray[index] == '' || cArray[index] == undefined) {
            jQuery(".slideshowContainer .overlay").hide();

        } else {
            jQuery(".slideshowContainer .overlay").show();
            jQuery(".slideshowContainer .overlay .title").html(tArray[index]);
            jQuery(".slideshowContainer .overlay .content").html(cArray[index]);

            var theLink = lArray[i];
            if (theLink == '' || theLink == undefined) {
                jQuery(".slideshowContainer .overlay .link").hide();
                jQuery(".slideshowContainer #slide-" + i).css('cursor', 'default');
            } else {

                jQuery(".slideshowContainer .overlay .link a").attr('href', lArray[index]);
            }

        }

        //hide caption if not populated
        if (caArray[index] == '' || caArray[index] == undefined) {
            jQuery(".slideshowContainer .caption_btn").hide();
        } else {
            jQuery(".slideshowContainer .caption span").html(caArray[index]);

        }


        //jQuery(".slideshowContainer #slide-"+i).click(gotoLink);//

        if (i > 0) { jQuery(".slideshowContainer #slide-" + i).hide(); }

    }

    if (iArray.length > 1) {
        resetInterval()
        //show nav arrows
        jQuery(".rightArrow").show();
        jQuery(".leftArrow").show();
    } else {
        jQuery(".caption_btn, .caption").css('margin-left', '47px');
    }
}


function createTeamSlideshow() {



    //for(var i = iArray.length-1; i >= 0; i--){
    for (var i = 0; i < iArray.length; i++) {

        jQuery(".slideshow").append('<div id="slide-' + i + '" class="team_slide" ><img src="' + iArray[i] + '" border="0" href="#selected_slide_' + i + '" /></div>')
        var toolTip = '<div class="toolTip_team"><img src="' + basePath + '/images/tooltip_arrow_up.png" border="0"/><div class="boundingBox"><div class="name">' + nArray[i] + '</div><div class="position">' + tArray[i] + '</div></div></div>';
        jQuery('#slide-' + i).append(toolTip);

        //create the pop up box
        var selectedBox = '<div id="selected_slide_' + i + '" class="selected_slide"><div class="selected_inner"><div class="topBox" style="background-image:url(\'' + siArray[i] + '\');"><div class="textBox"><div class="name">' + nArray[i] + '</div><div class="position">' + tArray[i] + '</div><div class="quote">' + caArray[i] + '</div></div></div><div class="content">' + cArray[i] + '</div></div></div>';
        jQuery('#slide-' + i).append(selectedBox);



        //set the width of the slide image
        //var img_width = jQuery(".slideshowContainer #slide-"+i).find('img').width();
        //jQuery(".slideshowContainer #slide-"+i).css('width',img_width);



        var width = parseInt(jQuery(".slideshowContainer #slide-" + i).outerWidth());

        if (i > 0) {
            //			var p = parseInt(i-1);
            //			var prev_pos = jQuery(".slideshowContainer #slide-"+p).css('left');
            //			
            //			 var left = parseInt(jQuery(".slideshowContainer #slide-"+p).width()) + parseInt(prev_pos);
            //		     //hide if cannot be viewed in containing area
            //			 if( ((left + width) >parseInt(jQuery(".slideshowContainer").width())) && i>=5){
            //			
            //				 jQuery(".slideshowContainer #slide-"+i).hide();
            //				 
            //			 }
            var left = width * i;
            jQuery(".slideshowContainer #slide-" + i).css('left', left + 'px');

        }




        jQuery(".slideshowContainer #slide-" + i).bind({

            mouseover: function(index) {
		//alert('in function mouseover slide!');
                var pos = jQuery(this).offset();

                var left = jQuery(this).width() / 2 - jQuery(this).children('.toolTip_team').outerWidth() / 2;
                var top = jQuery(this).height() - jQuery(this).height() / 4;

                jQuery(this).children('.toolTip_team').css({ 'left': left + "px", 'top': top + "px" }).show();

                //place the arrow for the tool tip
                var arrowLeft = jQuery(this).children('.toolTip_team').outerWidth() / 2 - jQuery(this).children('.toolTip_team').children('img').outerWidth() / 2;
                jQuery(this).children('.toolTip_team').children('img').css({ 'left': arrowLeft + "px" });

                //change background image
                var src = jQuery(this).children('img').attr('src');

//alert(src);
                if (src.indexOf("-Over") == -1) {
                    src = src.replace('-Static', '-Over');
                }


                jQuery(this).children('img').attr('src', src);

            },
            mouseout: function() {
                jQuery(this).children('.toolTip_team').hide();

                var src = jQuery(this).children('img').attr('src');
                src = src.replace("-Over", "-Static");
                jQuery(this).children('img').attr('src', src);

            }
        });

        jQuery('.team_slide').each(function() {
            jQuery(this).find('img').fancyZoom({ directory: popupDir, top: '10px' });
        });


    }
    index = 4;

    jQuery(".leftArrow").hide();
    jQuery(".rightArrow").show();


    //resetInterval()
}


function gotoLink() {
    var id = jQuery(this).attr("id");
    var idSplit = id.split("-");
    var index = idSplit[1] * 1;

    var theLink = lArray[index];

    location.href = theLink;
}



function resetInterval() {
    clearInterval(interval);
    interval = setInterval(swapSlide, time);
}


jQuery(document).ready(function() {


    jQuery(".leftArrow").click(function() {
        if (!jQuery('.slide, .team_slide').is(':animated')) {
            if (slideshow != 'team') {
                resetInterval();
            }

            dir = "b"; swapSlide();
        }
    });

    jQuery(".rightArrow").click(function() {
        //check if any animations are happening

        if (!jQuery('.slide, .team_slide').is(':animated')) {

            if (slideshow != 'team') {
                resetInterval();
            }
            dir = "f"; swapSlide();
        }

    });




    jQuery(".altContainer").mouseover(stopAltSlideshow);
    jQuery(".altContainer").mouseout(startAltSlideshow);

    jQuery('.slideshowContainer .caption_btn').click(function() {

        jQuery(this).prev().children().hide();

        jQuery(this).prev().animate({ width: 'toggle' }, 'fast',
				function() {
				    jQuery(this).children().fadeIn('fast');
				}
			);
        jQuery(this).hide();

    });


    jQuery('.slideshowContainer #caption_close').click(function() {

        jQuery(this).parent().children().fadeOut('fast');

        jQuery(this).parent().animate({ width: 'toggle' }, 'fast', function() {

            jQuery(this).next().show();
        });
    });



});




