var kc = kc || {};

$.fn.equalHeight = function(e){
	var p = this.parent(),
		l = this.length,
		max = 0;
		
	while(l--){
		max = (max > this.eq(l).height()) ? max : this.eq(l).height();
	}
	//	this.detach().height(max).appendTo(p);
	//Optimize by detaching the set, adjusting heights, and appending. need do differentiate each parent, though.
	//In the meantime, just accept the reflow.

	return this.height(max);;
};

$.fn.mediaGallery = function(rev){
	rev == rev || false;
	
	var	li = this.children()
	,	last = li.last()
	,	first = li.first()
	,	lastpos = parseInt(last.css('left'))//+w;
	;
	
	if(rev){
      this.height(last.height())
		last.insertBefore(first).css('left',(last.width()*-1));
		li.animate({left:'+=200px'},100);
	}
	else{
        this.height(first.height())
		li.animate({left:'-=200px'},100,function(){

			if($(this).index()==0){
				first.css('left',lastpos).insertAfter(last);
			}
		})	
	}
	
	return this;
};

$.fn.cyclenews = function(obj){
	var c = this.children(obj)
	,	x = this
	,	rotationTime = 3500
	,	timer
	,	maintimer
	,	par = $('<div class="cyclenews" />')
	;

	function anim(){
		var cur = c.filter(':visible')
		//,	p = cur.parent()
		,	w = x.width()
		;

		cur.animate({'left':'-='+w},100,function(){
			$(this).next().show().each(function(){
				par.animate({'height':$(this).height()},100)
			}).animate({'left':0},100).end().hide().appendTo(par).css('left',w)
		})

		timer = setTimeout(arguments.callee, rotationTime);
	}

	par.insertBefore(c.first()).append(c).height(c.first().height()).bind('mouseenter mouseleave',function(e){
	    if(e.type == 'mouseenter'){
	    clearTimeout(timer);
	    }
	    else{
	        anim();
	    }
	});
	c.width(x.width()).addClass('cyclecopy').not(':first').hide();	
	mainTimer = setTimeout(anim,rotationTime);

	return this;
}

kc.query =  (function () {
	var qString, queryStart, query, parts, bits, subbits, returnVals = {};
	qString = window.location.toString();
	queryStart = qString.indexOf('?');
	if (queryStart==-1) {
		return returnVals;
	}
	query = qString.substring(queryStart + 1, qString.length);
	parts = query.split("&");
	for (var i=0; i<parts.length; i++) {
		bits = parts[i].split("=");
		if (bits[1]) {
			subbits = bits[1].split("#");
			returnVals[bits[0].toLowerCase()] = subbits[0]; // query properties are lowercase!
		}
	}
	return returnVals;
}) () // self-invoking!

function brandribbon(rev){
var list = $('#br_ul').children()
,    range = (list.length/2)+1
,    slice = (rev) ? list.slice(0,range) : list.slice(range, range*2)
,    len = slice.length
,    px = 0
;

if(!$('#br_ul').length){
	return false;
}

while(len--){
    px-=slice.eq(len).height();
}

if(rev){
list.animate({'top':px},250,function(){
    list.css('top',0);
    slice.appendTo(list.parent());
})
}
else{
    slice.prependTo(list.parent());
    list.css('top',px);

list.animate({'top':'-='+px},250,function(){

})
}
kctimer = setTimeout(function(){brandribbon()},4000)
}

$(function(){
	$('.colunit').equalHeight();
	$('.news').equalHeight();
	$('#continentlist').find('a').equalHeight().click(function(e){
		var t = $(this)
		,	x = $('#'+t.attr('rel'))
		;
		
		e.preventDefault();
		t.addClass('sel').parent().siblings().find('a').removeClass('sel');
		x.show().siblings('.accordion').hide();
	}).eq(0).addClass('sel');
	
	$('.accordion').accordion().not(':first').hide();
	$('table').not('.ui-accordion-content').each(function(i,e){
	    $(e).find('tr:odd').addClass('alt')
	});
	$('.gallery').filter(':last').addClass('lastgallery');
	$('.current').parents('ul').show();		
    $('#navtop a:contains("' + ($('.LandingLink').text() == '' ? 'NoLandingLink' : $('.LandingLink').text()) + '")').addClass('primaryselect');        
	/*$('#frmSearch')//.find(':submit').hide().end()
	.find('label').bind('click',function(e){ 
		$(e.target).parent().submit();
	})*/
$('#navtwo')//.find(':submit').hide().end()
	.find('label').bind('click',function(e){ 
		//$(e.target).parent().submit();
window.location.href="/search.aspx?txtSearch=" + $('#txtSearch').val();
	})

$('#txtSearch').keypress(function(event) {
  if (event.keyCode == '13' && $('#txtSearch').val() != "") {
event.preventDefault();
    window.location.href="/search.aspx?txtSearch=" + $('#txtSearch').val();
   }
});


	$('#frmSearch').hide();
	$('#subSearch').hide();  
	$('.D1aBottom').each(function(){
	    $(this).appendTo($(this).parents('.ui-accordion-content'))
	}).parents('.accordion').accordion();
	
	brandribbon()

	$('#brandribbon').bind('mouseenter mouseleave',function(e){
	if(e.type == 'mouseenter'){
	    clearTimeout(kctimer)
	}
	else{
	    brandribbon();
	}
	})
});

$(function(){
	var ul = $('.gallery_list')
	,	w = 200
	;

	$('li',ul).each(function(i,e){
		$(e).css('left',i*w);
	})
	
	$('#gl_fwd').click(function(){
		$('.gallery_list').mediaGallery();
	})
	
	$('#gl_rev').click(function(){
		$('.gallery_list').mediaGallery(1);
	})
})

$('<div>',{
id:'media_overlay',
html:'<div id="mo_flash"/>'
}).prependTo('#main').each(function(){
var params = {
	allowScriptAccess: "always",
	bgcolor: "#ffffff",
	wmode: "opaque"
};
var flashvars = {};
var attributes = {id:"mo_video"};
swfobject.embedSWF("/swf/worldmap.swf", "mo_flash", "580", "300", "9.0.45", "/swf/expressinstall.swf", flashvars, params, attributes);
})

function PostJobLocandDept(url,jobcity,jobcategoryid)
{
  var myForm = document.createElement("form");
  myForm.method="post";
  myForm.action = url;
  myForm.target="_blank";
  var myParameterName =new Array("txtFromDate","txtToDate","cboJobTitle","cboCity","cboState","cboRadius",
                                "txtRadiusValue","rdoRadiusType","cboCountry","cboJobCategory","txtKeyWord",
                                "txtReqID","txtHiringManager","txtRecruiter");
 var myParamterValue = new Array("","","",jobcity,"","0","0","","CA,PR,GB,US",jobcategoryid,"","","","","");
 for(var i=0;i<myParameterName.length;i++)
 {
  var myInput = document.createElement("input");          
  myInput.setAttribute("name",myParameterName[i]);
  myInput.setAttribute("value",myParamterValue[i]);   
  myInput.setAttribute("style","display:none");
  myForm.appendChild(myInput);
}
  
  //myForm.appendChild(myInput);  
  document.body.appendChild(myForm);
  myForm.submit();
}

function PostJobLocandTitle(url,jobcity,jobRequisitionid,jobKeyword)
{
  var myForm = document.createElement("form");
  myForm.method="post";
  myForm.action = url;
  myForm.target="_blank";
  var myParameterName =new Array("txtFromDate","txtToDate","cboJobTitle","cboCity","cboState","cboRadius",
                                "txtRadiusValue","rdoRadiusType","cboCountry","cboJobCategory","txtKeyWord",
                                "txtReqID","txtHiringManager","txtRecruiter");
 var myParamterValue = new Array("","","",jobcity,"","0","0","","CA,PR,GB,US","0",jobKeyword,jobRequisitionid,"","");
 for(var i=0;i<myParameterName.length;i++)
 {
  var myInput = document.createElement("input");          
  myInput.setAttribute("name",myParameterName[i]);
  myInput.setAttribute("value",myParamterValue[i]);     
  myInput.setAttribute("style","display:none");
  myForm.appendChild(myInput);  
}
  
  //myForm.appendChild(myInput);  
  document.body.appendChild(myForm);
  myForm.submit();
}

function PostJobCategoryStateandTitle(url, jobCategory, state, jobcity) {
    var myForm = document.createElement("form");
    myForm.method = "post";
    myForm.action = url;
    myForm.target = "_blank";
    var myParameterName = new Array("txtFromDate", "txtToDate", "cboJobTitle", "cboCity", "cboState", "cboRadius",
                                "txtRadiusValue", "rdoRadiusType", "cboCountry", "cboJobCategory", "txtKeyWord",
                                "txtReqID", "txtHiringManager", "txtRecruiter");
                                
    var myParamterValue = new Array("", "", "", jobcity, state, "0", "0", "", "CA,PR,GB,US", jobCategory, "", "", "", "");
    for (var i = 0; i < myParameterName.length; i++) {
        var myInput = document.createElement("input");
        myInput.setAttribute("name", myParameterName[i]);
        myInput.setAttribute("value", myParamterValue[i]);
        myInput.setAttribute("style", "display:none");
        myForm.appendChild(myInput);
    }    
    document.body.appendChild(myForm);
    myForm.submit();
}

var initializeSchoolSelector = function(){
  $(".droparrow").click(function(){
    $(".school-selector-field p a").toggleClass("open");
    $(".school-selector-list").toggle();
  });
  $(".school-selector-list a").click(function(e){

    var ClickedSchool =$(this).attr("title");
    e.preventDefault(); 
    var SchoolEvent = null;    

var schoolName, schoolTestimonialName, schoolTestimonialDesignationRole;
var schoolTestimonialDepartment,schoolTestimonialDescription,secondaryContentTitle,secondaryContentDescription;
var event1,eventLocation,eventDescription,eventTime,eventdate;
var schoolTestimonialImage;
var iCount; var strHtml; 
var DateFormat;
var MaxNumberOfEvetns = 15;
var ImagePath = "http://www.cms.kimberly-clark.com/UmbracoImages/";  
// Setting the Images path based on the URL
if(window.location.href.indexOf(".kimberly-clark.com") > 0 || window.location.href.indexOf(".dev.preview.kimberly-clark.com") > 0)
    ImagePath = "http://www.dev.cms.kimberly-clark.com/UmbracoImages/";
else if(window.location.href.indexOf(".testqa.kimberly-clark.com") > 0 || window.location.href.indexOf(".qa.preview.kimberly-clark.com") > 0)
    ImagePath = "http://www.testqa.cms.kimberly-clark.com/UmbracoImages/";
else if(window.location.href.indexOf(".testdev.kimberly-clark.com") > 0 || window.location.href.indexOf(".testdev.preview.kimberly-clark.com") > 0)
    ImagePath = "http://www.testdev.cms.kimberly-clark.com/UmbracoImages/";
else 
    ImagePath = "http://www.cms.kimberly-clark.com/UmbracoImages/";     
    
//------------------------------------------------
            $.ajax({
                 type: "GET",
                 cache: false,
                 url:"/Careers/CommonFunctions/getSchoolContent.ashx",
                 //url:"getContentSchools.ashx",
                 data:"school=" + ClickedSchool,
                 dataType: "xml",
                 success: function(xml) {
                 $(xml).find('School').each(function(){                 
                                  schoolName =  $(this).find('schoolName').text()                                  
                                  schoolTestimonialName = $(this).find('schoolTestimonialName').text()
                                  schoolTestimonialDesignationRole=  $(this).find('schoolTestimonialDesignationRole').text()
                                  schoolTestimonialDepartment=  $(this).find('schoolTestimonialDepartment').text()
                                  schoolTestimonialDescription=  $(this).find('schoolTestimonialDescription').text()
                                  secondaryContentTitle = $(this).find('schoolDescriptionTitle').text()
                                  secondaryContentDescription= $(this).find('schoolDescription').text()
                                  schoolTestimonialImage = ImagePath + $(this).find('school').text().replace('~','');                                                                  
                                  strHtml=""; iCount=1;                                  
                                  for(var iEvent=1;iEvent<=MaxNumberOfEvetns;iEvent++)
                                  {                 
										eventLocation=$(this).find('event' + iEvent + 'Location').text()                                                                  
										eventDescription = $(this).find('event' + iEvent + 'Description').text()
										eventTime = $(this).find('event' + iEvent + 'Time').text()
										eventdate = $(this).find('event' + iEvent + 'Date').text();										
										//DateFormat = eventdate;
										//create table based on number of events										
										if((eventLocation + eventDescription + eventTime + eventdate) != '')
										{
										    if(eventdate.indexOf('T')> 0)
										        eventdate = eventdate.substring(0,eventdate.indexOf('T'));
											strHtml += iCount % 2 == 1? "<tr>": "<tr class='alternatingrow'>";
											strHtml += "<td>" + eventLocation+"</td><td>"+eventTime+"</td><td>"+eventdate+" </td><td>"+eventDescription+"</td></tr>";
											iCount= iCount+ 1;
										}										
								}
								
								if(strHtml == '')
									strHtml = "<tr><td colspan='4'>No event exists for the " + schoolName + "</td></tr>";								
								
									$("#school-content").load("/Careers/CommonFunctions/SchoolSelectorTemplate.html",null,function(response)
									{                         
										$("#school-content").html($("#school-content").html().replace('#schoolName#',schoolName));
										$("#school-content").html($("#school-content").html().replace('#schoolTestimonialName#',schoolTestimonialName));
										$("#school-content").html($("#school-content").html().replace('#schoolTestimonialDesignationRole#',schoolTestimonialDesignationRole));
										$("#school-content").html($("#school-content").html().replace('#schoolTestimonialImage#',schoolTestimonialImage));
										$("#school-content").html($("#school-content").html().replace('#schoolTestimonialDepartment#',schoolTestimonialDepartment));
										$("#school-content").html($("#school-content").html().replace('#schoolTestimonialDescription#',schoolTestimonialDescription));
										$("#school-content").html($("#school-content").html().replace('#secondaryContentTitle#',secondaryContentTitle));
										$("#school-content").html($("#school-content").html().replace('#secondaryContentDescription#',secondaryContentDescription));
										$("#school-content").html($("#school-content").html().replace('#tablecontent#',strHtml));										
										if((schoolTestimonialName+schoolTestimonialDesignationRole+schoolTestimonialDepartment+schoolTestimonialDescription) != '')
										{										   
										   $("#school-content").html($("#school-content").html().replace('#DisplayStyle#',"student-feature"));
										}
										else
										{										    
										   $("#school-content").html($("#school-content").html().replace('#DisplayStyle#',"student-feature-hide"));															
										}
									}); //HTML load ends
                                
                                }); //close  each(
                                
                                //close the widget
                                $(".school-selector-field p a").toggleClass("open");
                                $(".school-selector-list").toggle();
                 },
                 error:function(XMLHttpRequest, textStatus, errorThrown){
                 //alert("Error!!!" + errorThrown );
                 }
             });   //first ajax call ends
             //second ajax call to retrive events based on school selected.
           
                  
                       
   });
}

var initStory1=function(){
        var b=$(".scroll-pane"),a1=$(".scroll-content1");
        var g=$(".scroll-bar1").slider({slide:function(h,i){
            if(a1.width()>b.width()){a1.css("margin-left",Math.round(i.value/100*(b.width()-a1.width()))+"px")}else{a1.css("margin-left",0)}}});
            
                var f=g.find(".ui-slider-handle").mousedown(function(){g.width(f.width())}).mouseup(function(){
                g.width("100%")}).append("<span class='ui-icon ui-icon-grip-dotted-vertical'></span>").wrap("<div class='ui-handle-helper-parent'></div>").parent();b.css("overflow","hidden");
                function e(){var i=a1.width()-b.width();var j=i/a1.width();var h=b.width()-(j*b.width());
                    g.find(".ui-slider-handle").css({width:h,"margin-left":-h/2});f.width("").width(g.width()-h)}function c(){
                        var j=b.width()-a1.width();var i=a1.css("margin-left")==="auto"?0:parseInt(a1.css("margin-left"));var h=Math.round(i/j*100);g.slider("value",h)}function d(){var h=a1.width()+parseInt(a1.css("margin-left"),10);var i=b.width()-h;if(i>0){a1.css("margin-left",parseInt(a1.css("margin-left"),10)+i)}}$(window).resize(function(){c();e();d()});
                        setTimeout(e,10)};

var initStory2=function(){
        var b=$(".scroll-pane"),a2=$(".scroll-content2");                        
        var g=$(".scroll-bar2").slider({slide:function(h,i){
            if(a2.width()>b.width()){a2.css("margin-left",Math.round(i.value/100*(b.width()-a2.width()))+"px")}else{a2.css("margin-left",0)}}});
            
                var f=g.find(".ui-slider-handle").mousedown(function(){g.width(f.width())}).mouseup(function(){
                g.width("100%")}).append("<span class='ui-icon ui-icon-grip-dotted-vertical'></span>").wrap("<div class='ui-handle-helper-parent'></div>").parent();b.css("overflow","hidden");
                function e(){var i=a2.width()-b.width();var j=i/a2.width();var h=b.width()-(j*b.width());
                    g.find(".ui-slider-handle").css({width:h,"margin-left":-h/2});f.width("").width(g.width()-h)}function c(){
                        var j=b.width()-a2.width();var i=a2.css("margin-left")==="auto"?0:parseInt(a2.css("margin-left"));var h=Math.round(i/j*100);g.slider("value",h)}function d(){var h=a2.width()+parseInt(a2.css("margin-left"),10);var i=b.width()-h;if(i>0){a2.css("margin-left",parseInt(a2.css("margin-left"),10)+i)}}$(window).resize(function(){c();e();d()});
                        setTimeout(e,10)};





//Added for Video - CHG0063408
$(function() {
    $('<div>', {
        id: 'media_overlay',
        html: '<div id="mo_flash"/><img src="/images/close.png" id="mo_close" />'
    }).prependTo('#main');

    $('a').filter('[href$=".mp4"],[href$=".flv"]').unbind('click').bind('click', function(e) {
        var path = $(this).attr('href');

        $('#media_overlay').show()
        $f('mo_flash',
			{
			    src: '/images/flowplayer-3.2.5.swf',
			    wmode: 'opaque'
			},
			{
			    key: '#@6763637a425d2643b30',
			    clip: {
			        url: path,
			        autoPlay: true,
			        autoBuffering: true

			    }
			}
		);
        e.preventDefault();
    })

    $('#mo_close').live('click', function() {
        $f('mo_flash').close();
        $('#media_overlay').hide();
    })
    /*

		.each(function(){
    var params = {
    allowScriptAccess: "always",
    bgcolor: "#ffffff",
    wmode: "opaque"
    };
    var flashvars = {};
    var attributes = {id:"mo_video"};
    swfobject.embedSWF("/swf/worldmap.swf", "mo_flash", "580", "300", "9.0.45", "/swf/expressinstall.swf", flashvars, params, attributes);
    })
    */

})
