jQuery.fn.headerHomepage = function (options) {
    //the current obj;
    var element = this;
    //set up the following arrays to hold xml data
    var ImageName = new Array();
    var Title = new Array();
    var Comments = new Array();
    var LinkTo = new Array();
	var Tracking = new Array();
	var linkArray = new Array();

    //set up the default options
    var defaults = {
        xmlFile: '',
        width: "730",
        height: "287",
        fadeDuration: "1000",
        duration: "7000",
        imagePath: "gallery/",
        appImagePath: "images/",        
        fadeFX:'fade'
    };
    // Extend our default options with those provided.
    var settings = $.extend(defaults, options);
	settings.appImagePath = settings.appImagePath + "fragments/hp_jquery_mainfeat/images/";
    // lets size div accordingly options
    $(element).css('width', settings.width);
    $(element).height(settings.height);
    // this is use to cover the href on the nav btns
    $(element).prepend('<div id="hp-nav-wrapper"></div>');
    //this will hold the page numbers
    $(element).prepend('<div id="hp-nav"></div>');
   
    $("#hp-nav:first-child").append('<span id="hp-next"></span>');
    $("#hp-nav:first-child").prepend('<span id="hp-prev"></span>');
    
    $('#hp-nav-wrapper').css({
        'width': settings.width,
        'height': 25
    });
    // fires of the ajax event to get the xml
    $.ajax({
        type: "POST",
        url: settings.xmlFile,
        dataType: "xml",
        success: function (xmlData) {
            parseXml(xmlData);

        },
        beforeSend: function () {
            showLoading();
        },
        complete: function () {
            removeLoading();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $(element).append("<div id='hf-message' style='color:red'>Error: loading XML file " + textStatus + "</div>");
        }
    });

    function removeLoading() {
        $('#hf-message').remove();
    }

    function showLoading() {
        $(element).append("<div id='hf-message'>loading images......</div>");
    }

    function outPut(images) {
        var imgLenght = images.length;
        for (var i = 0; i < imgLenght; i++) {
            $(element).append("<img id='"+i+"' rel='"+LinkTo[i]+"' width='" + settings.width+"' height='"+settings.height+"' src='" + settings.imagePath + images[i] + "'/>\n");
        }
		$('#headerHomePage').cycle({
                fx:  settings.fadeFX,
                speed:  'slow',
                pager:  '#hp-nav',
                speed:  2500,
                next:   '#hp-next', 
                prev:   '#hp-prev',
                //expose pager function to add images
                pagerAnchorBuilder: function(idx, slide) { 
					return '<a href="#" class="pager"></a>'; 
                } ,
        		slideExpr: 'img'
            });
            $('#headerHomePage img').click(function (){
              
			   if (Tracking[$(this).attr('id')] != "not set" && Tracking[$(this).attr('id')].search("recordOutboundLink") >= 0){
					eval(Tracking[$(this).attr('id')]);										
			   }else if (Tracking[$(this).attr('id')] != "not set"){
					eval(Tracking[$(this).attr('id')]);				  
			  		document.location.href = $(this).attr('rel');
			   }else{
					document.location.href = $(this).attr('rel');
			   }
				//console.log($(this));
				
				
				
              }).css('cursor', 'pointer');
            
            $('#hp-next').appendTo('#hp-nav');
            
            $("#hp-nav:first-child").prepend('<a class="pause" id="pauseButton" href="#"><img src="'+ settings.appImagePath +'hp_mainfeat_pause.gif"></a>');
            $('#pauseButton').click(function() {
             
            	
            	var obj = $(this);
                if (obj.hasClass('pause')) {
                    obj.removeClass('pause').addClass('play').text('Play');
                    obj.html('<img src="'+ settings.appImagePath +'hp_mainfeat_play.gif">');
                    
                    $('#headerHomePage').cycle('pause'); 
                } else if (obj.hasClass('play')) {
                    obj.removeClass('play').addClass('pause').text('Pause');
                    $('#headerHomePage').cycle('resume');
                    obj.html('<img src="'+ settings.appImagePath +'hp_mainfeat_pause.gif">');
                }
            });

            
    
    }
   
    function parseXml(xmlData) {
    	var searchNode = "\\[nodeName=wcm\\:row\\]";
		var spot = 0;
    	$(xmlData).find(searchNode).each(function () {    		
    		switch ($(this).attr('name')) {
            case "ImageName":
                start = $(this).text().indexOf(",'") + 2;
                end = $(this).text().lastIndexOf("'");
                image = "idcplg?IdcService=GET_FILE&dDocName=" + $(this).text().slice(start, end) + "&RevisionSelectionMethod=latestReleased&Rendition=Web&allowInterrupt=1&noSaveAs=1";
                ImageName.push(image);
                break;
             case "LinkTo":				
				slideLink = $(this).text();
				//changed: the last quote may not be the one we want...
				//slideLink = slideLink.substring(slideLink.indexOf('href="')+6, slideLink.lastIndexOf('"')); 
				slideLink = slideLink.substring(slideLink.indexOf('href="')+6);
				slideLink = slideLink.substring(0,slideLink.indexOf('"')); 
				  
				slideLink = slideLink.replace('[!--$ssServerRelativeSiteRoot--]',settings.imagePath);
                LinkTo.push(slideLink);               
				if($(this).text().search("onclick") >= 1){
					clickEvent = $(this).text();
					clickEvent = clickEvent.substring(clickEvent.indexOf('onclick="')+9,clickEvent.indexOf(';')+1);				
					if(clickEvent.search("recordOutboundLink") >= 0){
						linkObj =  new Object();
						linkObj.href = slideLink; 
						
						//target _blank will only function on outgoing url's - provided the analytic event is set...which is a good thing?
						if($(this).text().search("_blank") >= 0){
							linkObj.target = "_blank";							
						}
						linkArray[spot]=  linkObj;
						clickEvent = clickEvent.replace("this","linkArray["+spot+"]");
						spot = spot+1;																
					}
					Tracking.push(clickEvent);					
				}else{Tracking.push("not set");}
				
				//console.log($(this).get().getAttributeNode('onclick').value));                 
				//can not perform _blank targets with document.location - so I do not think this is functioning
				//if($(this).text().search("_blank") >= 1){
					//LinkTo.push(slideLink);
				//}else{
					//LinkTo.push("/"+slideLink);	
				//}
				
				break;
            }
			 
			  //debug(LinkTo);
        });
        //add the first slide stuff

        outPut(ImageName);
    }
};

function debug(obj) {
    if (window.console && window.console.log) window.console.log(obj);
}

