﻿// On load function
$(document).ready(function(){
  try{
  sdMenuInit();
  tabEx();
  logoright();
  $(starttt);  //Start Tooltip obj  - on first call is used
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(starttt);
  }
  catch(err){}
  });

// SD Menu minimized
function SDMenu(a){if(!document.getElementById||!document.getElementsByTagName)return false;this.menu=document.getElementById(a);this.submenus=this.menu.getElementsByTagName("div");this.remember=true;this.speed=8;this.markCurrent=true;this.oneSmOnly=false}function sdMenuInit(){myMenu=new SDMenu("my_menu");myMenu.init()}var myMenu;SDMenu.prototype.init=function(){var a=this;for(var b=0;b<this.submenus.length;b++)this.submenus[b].getElementsByTagName("span")[0].onclick=function(){a.toggleMenu(this.parentNode)};if(this.markCurrent){var c=this.menu.getElementsByTagName("a");for(var d=0;d<c.length;d++)if(c[d].href==document.location.href){c[d].className="current";break}}};SDMenu.prototype.toggleMenu=function(a){if(a.className=="collapsed")this.expandMenu(a);else this.collapseMenu(a)};SDMenu.prototype.expandMenu=function(a){var b=a.getElementsByTagName("span")[0].offsetHeight;var c=a.getElementsByTagName("a");for(var d=0;d<c.length;d++)b+=c[d].offsetHeight;var e=Math.round(this.speed*c.length);var f=this;var g=setInterval(function(){var c=a.offsetHeight;var d=c+e;if(d<b)a.style.height=d+"px";else{clearInterval(g);a.style.height="";a.className="";f.memorize()}},30);this.collapseOthers(a)};SDMenu.prototype.collapseMenu=function(a){var b=a.getElementsByTagName("span")[0].offsetHeight;var c=Math.round(this.speed*a.getElementsByTagName("a").length);var d=this;var e=setInterval(function(){var f=a.offsetHeight;var g=f-c;if(g>b)a.style.height=g+"px";else{clearInterval(e);a.style.height="";a.className="collapsed";d.memorize()}},30)};SDMenu.prototype.collapseOthers=function(a){if(this.oneSmOnly){for(var b=0;b<this.submenus.length;b++)if(this.submenus[b]!=a&&this.submenus[b].className!="collapsed")this.collapseMenu(this.submenus[b])}};SDMenu.prototype.memorize=function(){if(this.remember){var a=new Array;for(var b=0;b<this.submenus.length;b++)a.push(this.submenus[b].className=="collapsed"?0:1);var c=new Date;c.setTime(c.getTime()+30*24*60*60*1e3);document.cookie="sdmenu_"+encodeURIComponent(this.menu.id)+"="+a.join("")+"; expires="+c.toGMTString()+"; path=/"}}
//---------------------------------------------------------------------------------------------------------------
//System Utilities
//----------------
//To skip any errors to client for x3 office
function noerr(){return true;}
function loadnoerr(){window.onerror = noerr;}

//===============================================================================================================
// Cookie utilities
//---------------------------------------------------------------------------------------------------------------
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

function setCookie(c_name,value){
var d = new Date();
d.setTime(d.getTime() + (30 * 24 * 60 * 60 * 1000));
document.cookie = c_name + "=" + value + "; expires=" + d.toGMTString() + "; path=/";
}



//===============================================================================================================
// Common Utilities
//---------------------------------------------------------------------------------------------------------------
//Give val depending on the object
function ValToObj(objid, val) {
    var obj = document.getElementById(objid.toLowerCase());
    if (val == null) { val = '' }
    try{tgn = obj.tagName.toUpperCase();
    if (tgn == "TD") { obj.innerHTML = val;}
    else if (tgn == "INPUT") {
        try { var wrapper = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(obj); wrapper.set_Value(val); }
        catch (err) { obj.value = val; } 
    }}
catch (err) {} 
}

function ValFromObj(objid) {
var obj = document.getElementById(objid.toLowerCase());
try{tgn = obj.tagName.toUpperCase();if (tgn == "TD") { return obj.innerHTML;}else if (tgn == "INPUT") {return obj.value}}
catch (err) {}}

function addDot(nStr)
{nStr += '';x = nStr.split(',');x1 = x[0];x2 = x.length > 1 ? ',' + x[1] : '';var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {x1 = x1.replace(rgx, '$1' + '.' + '$2');}	return x1 + x2;}




//===============================================================================================================
// Slide works
//---------------------------------------------------------------------------------------------------------------

var aystrnames
var aystrimages
var startindex
var lastindex
var pathproducts

// Select the product in the image
function clickslide(){ 
strfile = document.getElementById('lbldesc').firstChild.data  + '.aspx';
strfile = strfile.replace(" ", "-").replace(" ", "-").replace(" ", "-").replace(" ", "-");
if (pathproducts  ==  null){pathproducts = ''} // for bug as sometime the pathproducts remain undefined
strfile = pathproducts + strfile.toLowerCase();
location.href = strfile;
}

function clickprev(imagepath){
startindex = startindex - 1;
if (startindex < 1){document.getElementById('btprev').style.visibility = 'hidden';}
else {GiveVisibilityToBoth();}
FireOnObjects(imagepath);
}                  
                        
function clicknext(imagepath){
startindex = startindex + 1;
if (startindex > lastindex){document.getElementById('btnext').style.visibility = 'hidden';}
else {GiveVisibilityToBoth();}
FireOnObjects(imagepath);
}                       

function GiveVisibilityToBoth(){
document.getElementById('btprev').style.visibility = 'visible';
document.getElementById('btnext').style.visibility = 'visible';
}  

// Last step load the data on objects
function FireOnObjects(imagepath){
var imgslide = document.getElementById('imgslide');
imgslide.focus(); // needed to avoid selection on arrows
document.getElementById('lbldesc').firstChild.data = aystrnames[startindex];
if (aystrimages[startindex] == 'no image'){
    imgslide.style.color = 'black';
    imgslide.alt = aystrnames[startindex];
    imgslide.src = '';}
else{
    imgslide.style.color = 'White'
    imgslide.src = imagepath + aystrimages[startindex];}
} 

//Prepare variables on load                        
function loadaystr(strnames, strimages, sstartindex, slastindex, spathproducts){ 
var aynames = new Array();
var ayimages = new Array();
aynames=strnames.split(",");
ayimages=strimages.split(",");
aystrnames = aynames;
aystrimages = ayimages;
startindex = sstartindex;
lastindex = slastindex;
pathproducts = spathproducts;
}                        

                        
//===============================================================================================================
// Tab Image work
//---------------------------------------------------------------------------------------------------------------
var aySizes

var imgid; var pathimg; var imgFirstPart; var linkID; var ImageCount; //vars needed to load images

function LoadImgsPars(imgid1, pathimg1, imgFirstPart1, linkID1, ImageCount1){
imgid = imgid1;pathimg = pathimg1;imgFirstPart = imgFirstPart1;
linkID = linkID1;ImageCount = ImageCount1;
}


function ImagesSwitch(LinkId, ImgID, pathlink, imgFirstPart, ImgIndex){// When is cecked a small image in the list we display the relative big and reupdate the links for download 
//The ImgSizeFile(2) = "Big" size
document.getElementById(ImgID).src = pathimg + imgFirstPart + '_' + ImgSizeFile(2) + '_' + ImgIndex + '.jpg'
for (i=1;i<=5;i++)
    {
    var link = document.getElementById(LinkId + i)
    link.href = pathlink + imgFirstPart + '_' + ImgSizeFile(i) + '_' + ImgIndex + '.aspx';
    link.innerHTML = ImgSizeCaption(i) + '&nbsp;&nbsp;(' + aySizes[(5 * (ImgIndex - 1)) + i - 1] + ' Kb)';
    }  
}                


function ImgSizeFile(size){
var ay = ["Biggest","Big","Medium","Small","Smallest"];
return ay[size - 1];
}      
function ImgSizeCaption(size){
var ay = ["Molto Grande","Grande","Media","Piccola","Molto Piccola"]
return ay[size - 1];
}      
function LoadSizes(strSizes){
var ay = new Array();
ay=strSizes.split(",");
aySizes = ay
}


//===============================================================================================================
//Validators utilities
//---------------------------------------------------------------------------------------------------------------

function ShowMPEclient(){ //MPE = ModalPopupExtender
var mpe= $find('mpecv');
try{Page_ClientValidate();
if(!Page_IsValid)
{mpe.show();}}
catch(err){}
}


// hide MPE on escape or enter 
function addhanlder(e){$addHandler(document, "keydown", onkeydown);}
function onkeydown(e){if((e && e.keyCode == Sys.UI.Key.enter)||(e && e.keyCode == Sys.UI.Key.esc))
{var mpe = $find('mpe');if (mpe != null){
mpe.hide();
//For UP solution: document.location.reload(true);
}}}

// Update Panel Load Event
function OnAsyncLoad(fldfocus){
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(asyncPutFocus);
deffocus = fldfocus}
var deffocus
//Put focus after MPE unload
function asyncPutFocus(sender, args){
if (args.get_panelsUpdated().length > 0){$get(deffocus).focus();}}


// help to put focus on tbox with watermark
function txtputfocus(ObjID){try{document.getElementById(ObjID).focus();}catch(err){}} 

function hidesummarydiv(){try{document.getElementById('summarydiv').style.display='none';}catch(err){}}

function FixContentValues(FldsAndValues){ay=FldsAndValues.split(",");for (i = 0; i < ay.length; i += 2) {ValToObj(ay[i], ay[i + 1]);}}


//Custom Validator: implement here with java for fields custom validation (use fldname preceeded by "cv") 
function CustomValidator(val, args) {
//alert(val.id);
if (val.id.substring(0,3) == 'cka'){//for all checkbox when not checked
var ckobj = document.getElementById(val.id.substring(3)); 
if (ckobj.checked){args.IsValid =  true;} else {args.IsValid = false;}}
//---------------------------
if (val.id == 'cvprivacy'){
var privacy = document.getElementById("privacy");       
    if (privacy.checked){args.IsValid = true;} else {args.IsValid = false;}}
//---------------------------
if (val.id == 'cvpwconfirm'){
var password = document.getElementById("password");  
var pwconfirm = document.getElementById("pwconfirm"); 
if (password.value == '***********' || pwconfirm.value == '***********'){args.IsValid = true;} //when fields are empty avoid to give error
else if (password.value == pwconfirm.value) {args.IsValid = true;} else {args.IsValid = false;}}
//---------------------------
if (val.id == 'cvpurchase_date'){
var d1 = DateFromElement("purchase_date")
var d2 = new Date();
if(d1 > d2){args.IsValid = false;}else {args.IsValid = true;}}
}




function DateFromElement(elem_date){
var str1 = document.getElementById(elem_date).value;
var dt1  = parseInt(str1.substring(0,2),10);
var mon1 = parseInt(str1.substring(3,5),10);
var yr1  = parseInt(str1.substring(6,10),10);
var date1 = new Date(yr1, mon1 - 1, dt1);
return date1
}


/* On keydown control the value over a checkbox by the key +/- y/n and display validator */
function kdcb(ev, cbid, dovalidator){
if ((ev.keyCode==107)||(ev.keyCode==89)){docheck(cbid, dovalidator, true)} /* +/y */
if ((ev.keyCode==109)||(ev.keyCode==78)){docheck(cbid, dovalidator, false)}/* -/n */
}
/* help for doing check */
function docheck(cbid, dovalidator, checked, begtag){
var cb = document.getElementById(cbid);
var bg = document.getElementById('lblbg' + cbid);
cb.checked=checked;
formatbg(checked,bg)
if (dovalidator){var v = document.getElementById(begtag + cbid);ValidatorValidate(v);}
cb.focus();return false;
}
/* OnClick help to display validator and format */
function occb(cbid, dovalidator, begtag){
if (dovalidator){var v = document.getElementById(begtag + cbid);ValidatorValidate(v);}
var cb = document.getElementById(cbid);
var bg = document.getElementById('lblbg' + cbid);
formatbg(cb.checked,bg)}

/*radio btn on click */
function ocrb(rbsname, lblbg){
//if (dovalidator){var v = document.getElementById(validator);ValidatorValidate(v);}
var rbs = document.getElementsByName(rbsname);
for (i=0; i<rbs.length; i++){var bg = document.getElementById(lblbg + i);formatbg(rbs[i].checked,bg)}}


function formatbg(ischecked, lblbg){
if (ischecked) {lblbg.style.background = 'white';lblbg.style.color = 'black';}else {lblbg.style.background = '#F0F8FF';lblbg.style.color = 'grey';}}
//===============================================================================================================
//Ace(Auto Complete Extender) utilities
//---------------------------------------------------------------------------------------------------------------
var gindex // Grid id index in case is a grid
var PrevKeyCode
var prevPrevKeyCode
var acedopb //Need to take ACE value in PostBack
//var acename

// kd allow to keep id field empty while the Ace value is not taken, in the strflds indicate the fields to refresh with empty
// when new website will be operative take these pars on PageRs col Autocomplete, so Grdi_Write will be free from onkeydown event 
function kdCustomers(ev) {kd(ev, "id_cmpny,city"); }
function kdProducts(ev) {kd(ev, "id_itm,item_code"); }
function kdProductsCode(ev){kd(ev, "id_itm,item_descr");}
function kdProductsDescrAndCode(ev){acedopb= true;}
function kdCustomersOnly(ev){acedopb = true;}
function kdBrandOnly(ev){acedopb=true;}
function kdAgentOnly(ev){acedopb=true;}
//function kdSearch(ev){kd(ev, "srcbox");}

function kd(ev, strflds) { //strflds is like "id_itm,item_code"
acedopb = false;
var l = strflds.length;if (l == 0) { return;};
var evobj = ev.srcElement? ev.srcElement : ev.target; 
gindex = getgindex(evobj.id)
if ((ev.keyCode > 47 && ev.keyCode < 91) && (PrevKeyCode > 47 && PrevKeyCode < 91)) {
    ay = strflds.split(",");
    var ub = ay.length;
    for (i = 0; i < ub; i += 1) {ValToObj(ay[i] + gindex, '')} 
}
prevPrevKeyCode = PrevKeyCode;
PrevKeyCode = ev.keyCode;
}

//Call to Web Service do not is used for GridWrite were values are take in callback (called from OU4_Objects sub Add_AutoComplete)
function AceTakeVals(source, Arg) {
    if (acedopb){__doPostBack(source._element.id,'')}
//    if (acedopb){window.setTimeout("__doPostBack('" + source._element.id + "','')", 10); }
    else{acename = source._serviceMethod;
    WebService.TakeRecsVal(acename, Arg.get_value(), FillVals);}
}

//Fired as Callback from WEB service, used now only in KD, for possible future needs of KD on grid_write
function FillVals(AyResults) {
var ub = AyResults.length;
for (i = 0; i < ub; i += 2) { 
ValToObj(AyResults[i] + gindex, AyResults[i + 1]);
}
} 

//Grid id index taken from field 
function getgindex(objid) {
    lc = objid.substring(objid.length - 3);
    if (lc > -1) { return lc; }
    else if (lc.substring(1) > -1) { return lc.substring(1) }
    else if (lc.substring(2) > -1) { return lc.substring(2) }
    else { return '' }
}


//===============================================================================================================
//Form Key Event
//---------------------------------------------------------------------------------------------------------------
//Go to fire default submit button if it is not on autocomplete (else the enter is need to select item)
function FireDefButton(ev, btnid){
if (ev.keyCode==13){
    if ((PrevKeyCode != 13 )||(prevPrevKeyCode == null)||(prevPrevKeyCode == 13)){
        if (document.activeElement.id == 'srcbox'){btnid = 'srcbox'}
        return WebForm_FireDefaultButton(ev, btnid); //Only in such case fire the button
        }
    else{return false} //Annull the enter event
    }
}

function focusonenter(event, objid){if(event.keyCode == 13){event.returnValue=false;event.cancel = true;$('#'+objid).click();}}



//===============================================================================================================
// Jquery Tooltip
//---------------------------------------------------------------------------------------------------------------
var ii = 0; var lasttt;

function tooltips(target_items, name){
 $(target_items).each(function(i){      
        if (lasttt != null && i == 0){$(lasttt).css({display:"none"})} // avoid on UP callback the prev tt remain visible
        tooltipsevents($(this));
        if($(this).attr("title") != ""){ // checks if there is a title
            ii++;
		    $("body").append("<div class='"+name+"' id='"+name+ii+"'><p>"+$(this).attr('title')+"</p></div>");
		    var my_tooltip = $("#"+name+ii);
            tooltipevent(my_tooltip, this, this.title, 700, 'top');
            $(this).removeAttr("title");
        }
	});
}

function tooltipsevents(obj){
var id = obj.context.id;
if (id.length > 4){if (id.substr(0, 4) == 'blcv')
    {var brand = obj.context.childNodes(0).childNodes(0).alt.substring(9, 30);
    var txt = 'Clicca qui per visualizzare i prodotti del brand </br>';
    obj.attr("title", txt  + brand);}}}



function tooltipevent(otooltip, ofire, msgtxt, fadeInto, pos){
var ww =  widerword(msgtxt);var l = msgtxt.length;
var w = 80 + (l * 1.2); if (w < (25 + (ww*4.7))){w = (25 + (ww*4.7))};if (w > 300){w = 300};
otooltip.css({width:w})
$(ofire).mouseover(function(){
        if (ofire.tagName.toLowerCase() == 'img'){otooltip.css({display:"none", visibility:"visible"}).fadeIn(fadeInto);} //for bug when move fast on img
        else {otooltip.css({opacity:0.9, display:"none"}).fadeIn(fadeInto);} 
}).mousemove(function(kmouse){
        h = otooltip.innerHeight()
        lasttt = otooltip;
        if(pos == 'top'){xd = w / 2; yd = 30 + h};
        if(pos == 'left'){xd = w + 30; yd = 0};
        if(kmouse.pageY-yd < 0){yd = -yd+30}; 
		otooltip.css({left:kmouse.pageX- xd, top:kmouse.pageY-yd});
}).mouseleave(function(){
         if (ofire.tagName.toLowerCase() == 'img'){ otooltip.css({visibility:"hidden"});} //for bug when move fast on img
        else {otooltip.stop().fadeOut(200);} 
});
}



function starttt(){tooltips("a,input,img,th,span,div","tooltip");}
function widerword(prhase){var wl = 0;var w = prhase.split(' ');
for (i = 0; i < w.length; i++){if (w[i].length > wl){wl = w[i].length;}} return wl;}







//========================
// DataTable Jquery Object
//---------------------------------------------------------------------------------------------------------------
function strcols(str){ay = str.split(",");var colssort = new Array();[ay.length];
for (var i = 0; i < ay.length; i++)
if (ay[i] !== '0')
{colssort[i] = null;}
else{colssort[i] = {'bSortable':false};}
return colssort;
}


function datatable(tableid, dofade, doscroll, strsort, dosort, cisum, cname){
var oTable = $('#' + tableid).dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bStateSave": true,
"bRetrieve": true,
"bSort": dosort,
"aoColumns":strcols(strsort),
"aLengthMenu":[[5, 10, 25, 50, -1], [5, 10, 25, 50, "All"]],
"oLanguage": {
	"sLengthMenu": "Mostra _MENU_ records per pagina",
	"sZeroRecords": "Nulla è stato trovato, spiacenti",
	"sInfo": "Records da _START_ a _END_, di _TOTAL_ totali",
	"sInfoEmpty": "Nessun records",
	"sInfoFiltered": ""
},
"fnFooterCallback": function (nRow, aaData, iStart, iEnd, aiDisplay ) { //Tooltip for possible column total
    if (cisum != null){
    var tot = 0;var totpage = 0;
    for (var i = 0; i < aaData.length ; i++) {tot += parseInt(aaData[i][cisum].replace(',','').replace('.',''));}       
    for (i = iStart; i < iEnd; i++) {totpage += parseInt(aaData[aiDisplay[i]][cisum].replace(',','').replace('.',''));}
    var hcol = $('#' + tableid).children()[0].getElementsByTagName('th')[cisum];
    var txt = "Somme della colonna '"+ cname + "'<br/>Nella pagina: "+ addDot(totpage)+ "<br/>Nel Totale: " + addDot(tot);
   $('#sumtt').remove();
   $("body").append("<div class='tooltipsum' id='sumtt'><p>"+txt+"</p></div>");
    var otooltip = $("#sumtt");
    tooltipevent(otooltip, hcol, txt, 200, 'left');
    }}
})
if(dofade == true){ofade([ 'x3tablecs', "fg-toolbar", "dataTables_info", "DataTables_sort_icon", "fg-button" ], 500);
ofade([ "DataTables_sort_wrapper"], 500);}

if(doscroll == true){$('html, body').animate({scrollTop:  $('#' + tableid).offset().top - 335}, 1100);}

oTable.css({visibility:"visible"});
}



//========================
// Jquery Effects
//---------------------------------------------------------------------------------------------------------------
function ofade(target_items, interval){$(target_items).each(function(i){
$('.' + this).css({display:"none"}).fadeIn(interval);
 })}

 function oslide(target_items, interval){$(target_items).each(function(i){
$('.' + this).css({display:"none"}).slideDown(interval);
//$('.' + this).css({display:"run-in"})
 })}

 function oshow(target_items, interval){$(target_items).each(function(i){
$('.' + this).show(interval);
 })}

 function ohide(target_items, interval){$(target_items).each(function(i){
$('.' + this).hide(interval);
 })}

function oslideup(prefix, target_items, interval){$(target_items).each(function(i){
$(prefix + this).css({display:"run-in"}).slideUp(interval);
})}

function oslidedown(prefix, target_items, interval,maxheight){$(target_items).each(function(i){
$(prefix + this).css({display:"none",height:maxheight+"px"}).slideDown(interval);
})}

//$(document.body).click(function () {
//$('#leftcolumn').hide(2000);
//$('#rightcolumn').hide(2000);
//});





//function slideheader(){
//var hmax = 100;var h = $('#header').attr("height");var cls = $('#headup').attr('class');
//if(cls == 'headup'){
//var nh = hmax;oslidedown("#", ["header"], 500,nh);
//setCookie('cheaderup','1');
//$('#logo').css({display:"none"})
//$('#headup').attr('class', 'headdown');
//}
//else{
//oslideup("#", ["header"], 500);
//setCookie('cheaderup','0');
//$('#logo').css({display:"run-in",top:24}).slideDown(1000);
//$('#headup').attr('class', 'headup');
//}
//}

//function logoright(){
//var logo = $('#logo');var l = $('#leftcolumn').offset().left + 1000;
//if($('#headup').attr('class') == 'headup'){logo.css({left:l,top:24,display:"run-in"})}
//else {logo.css({left:l,top:24,display:"none"})}

//$(window).resize(function(){
//    var l = $('#leftcolumn').offset().left + 1000;
//    if ((l < 1100)||($('#headup').attr('class') != 'headup'))
//        {logo.css({left:l,top:24,display:"none"})}
//    else if (l > 1099)
//        {logo.css({left:l,top:24,display:"run-in"})}
//});
//}

function slideheader(){
var hmax = 100;var h = $('#header').attr("height");var cls = $('#headup').attr('class');
if(cls == 'headup'){
var nh = hmax;oslidedown("#", ["header"], 500,nh);
setCookie('cheaderup','1');
$('#logo').css({display:"none"})
$('#headup').attr('class', 'headdown');
}
else{
oslideup("#", ["header"], 500);
setCookie('cheaderup','0');
$('#logo').css({display:"none"}).slideDown(1000);
$('#headup').attr('class', 'headup');
}
}

function logoright(){logopos();$(window).resize(function(){logopos();});}

function logopos(){
var l = $('#leftcolumn').offset().left + 1000;
if ((l < 1100)||($('#headup').attr('class') != 'headup'))
    {$('#logo').css({left:l,top:24,display:"none"})}
else if (l > 1099)
    {$('#logo').css({left:l,top:24,display:"run-in"}).slideDown(1000);}
 }

//========================
// Jquery Tab Panel
//---------------------------------------------------------------------------------------------------------------

function tabEx(){
if($(".panes").length == 0){return;}//Exit if the document has not tab
tabEffect(0)
$("a.tab").click(function () { // When a link is clicked
	tabClick(this)
});}

function tabClick(tabObj){
if(tabObj.className == 'tab tabcur'){return;} //exit if cliecked the same tab
$(".tabcur").removeClass("tabcur"); // switch all tabs off
$(tabObj).addClass("tabcur");// switch this tab on
tabEffect(500)
setCookie('tabcur', $(tabObj).attr("innerHTML"))
}

function tabEffect(timing){
$(".panes div h2").css({display:"none"})
$(".panes > div").slideUp(timing);// slide all content up (hide)
var content_show = $('.tabcur').attr("rel"); 
$("#" + content_show).slideDown(timing); //slide up (show)default tabcur 
}

function tabSelect(index){
tabClick($(".tabs li a")[index])
}











