
/**********************************************************************/
/*                                                                    */
/* This script contains functions and variables which are used for    */
/* all campaign-pages                                                 */
/*                                                                    */
/**********************************************************************/
$(document).ready( CampaignFormInit );
function CampaignFormInit() {
 // Colapse everything that should be colapsed
 $('#campaign_form div.campaign_colapsed').hide();
 // Add toggle function to the "after-campaign-link"
 $('#campaign_form h6.campaign_colapseToggle').click(
 CampaignForm.Toggle.AC
 );
 // Add toggle function to the products that contain Xtra information
 $('#campaign_form input.campaign_colapseToggle').each(
  function(i) {
   if(!$(this).attr('checked')) {
    var toggleParent = $(this).parents('div.campaign_product:first');
    var toToggle = $(toggleParent).find('div.campaign_expandable:first');
    $(toToggle).hide();
   }
   $(this).click(CampaignForm.Toggle.XI);
  }
 );
 // Add the links that will toggle the product-areas
 $('#campaign_form div.campaign_product_area:not(.campaign_notoggle) div.campaign_header').each(
 function(i) {
  var toToggle = $(this.parentNode).find('div.campaign_expandable:first');
  if( $(toToggle).hasClass('campaign_colapsed') ) {
 var thisTxt = CampaignForm.Txt.BtnShowAlterantives;
 var ex = '';
  } else {
 var thisTxt = CampaignForm.Txt.BtnHideAlterantives;
 var ex = ' expanded';
  }
  $(this).append(
   '<span class="campaign_toggleArea'+ex+'">' + thisTxt + '</span>'
  );
 }
 );
 $('#campaign_form span.campaign_toggleArea').click(
 CampaignForm.Toggle.PA
 );
 // Add links that will toggle more info for main offer
 $('#campaign_form div.campaign_more_info').each(
  function(i) {
   var toToggle = $(this).find('div.campaign_expandable:first');
  if( $(toToggle).hasClass('campaign_colapsed') ) {
 var thisTxt = CampaignForm.Txt.BtnShowDetails;
 var ex = '';
  } else {
 var thisTxt = CampaignForm.Txt.BtnHideDetails;
 var ex = ' expanded';
  }
  $(this).prepend(
   '<span class="campaign_toggleArea'+ex+'">' + thisTxt + '</span>'
  ); 
  }
 );
 $('#campaign_form div.campaign_more_info span.campaign_toggleArea').click(
 CampaignForm.Toggle.MI
 );
 // Remove HREF from popup-links in channel list
 if( $('#campaign_form div.campaign_channellist:first').is('div') ) {
 $('#campaign_form div.campaign_channellist:first label a').removeAttr('href');
 }
 // If telephony-services is present make sure you can't check
 // both "Alltid" and "Fritid". Since "Fritid" is included in "Always"
 if( $('#telephony_always').is('input:checkbox') &&
  $('#telephony_free').is('input:checkbox') ) {
   $('#telephony_always').click(function() {
    if( $('#telephony_always:checked').is('input') ) {
     $('#telephony_free').removeAttr('checked');
     $('#telephony_free').attr('disabled','disabled');   
    } else {
     $('#telephony_free').removeAttr('disabled');
    }
   });
 }
 CampaignForm.Validate.Init();
 CampaignForm.LB.Init();
}
var CampaignForm = {
 AnimSpeed : 250,
 Txt : {
  BtnShowAlterantives: 'Visa alternativ',
  BtnHideAlterantives: 'G\xF6m alternativ',
  BtnShowDetails: 'Visa detaljer',
  BtnHideDetails: 'D\xF6lj detaljer'  
 },
 Toggle : {
  AC : function() {
   var toToggle = $(this.parentNode).find('div.campaign_expandable:first');
   $(toToggle).slideToggle(CampaignForm.AnimSpeed);
   $(this).toggleClass('expanded');
  },
 
  XI : function() {
   var toggleParent = $(this).parents('div.campaign_product:first');
   var toToggle = $(toggleParent).find('div.campaign_expandable:first');
   if( $(this).attr('checked') ) {
   $(toToggle).slideDown(CampaignForm.AnimSpeed);
   } else {
    $(toToggle).slideUp(CampaignForm.AnimSpeed);
   }
  },
 
  MI : function() {
   var toggleParent = $(this).parents('div.campaign_more_info:first');
   var toToggle = $(toggleParent).find('div.campaign_expandable:first');
   $(toToggle).toggle(CampaignForm.AnimSpeed);
   $(this).toggleClass('expanded');
   if( $(this).hasClass('expanded') ) {
   $(this).text(CampaignForm.Txt.BtnHideDetails);
   } else {
   $(this).text(CampaignForm.Txt.BtnShowDetails);  
   }
  }, 
 
  PA : function() {
   var toggleParent = $(this).parents('div.campaign_product_area:first');
   var toToggle = $(toggleParent).find('div.campaign_expandable:first');
   $(toToggle).slideToggle(CampaignForm.AnimSpeed);
   $(this).toggleClass('expanded');
   if( $(this).hasClass('expanded') ) {
   $(this).text(CampaignForm.Txt.BtnHideAlterantives);
   } else {
   $(this).text(CampaignForm.Txt.BtnShowAlterantives);  
   }
  }
 },
 Validate : {
  Timer : false,
 Fields : {},
 Init : function() {
  /***********************************************************************/
 /*                                                                     */
  /*  The different types of validation                                  */
  /*  Any = Field contains anything                                      */
  /*  Num = Field contains only numbers (also allow - and space)         */
  /*  Mail = Field contains a correct e-mailaddress                      */
  /*  Match = Two fields contains same value ( field to match            */
  /*          have to be put in like Match[FieldId] )                    */
 /*  PN = Fields contain a social-security number                       */
   /*  XX = Field can contain anything or nothing (Just to show the check)*/
 /*  CB = Checkbox                                                      */
 /*  RB = Radiobtns, require name instead of id (not implemented)       */
 /*  ZIP = Field contains zip-code                                      */
 /*  M8 = Make sure 8-channels are selected                             */ 
 /*                                                                     */
 /*  Add a field by putting it's id as a key in a new item in the       */
 /*  array "CampignForm.Validate.Fields"                                */
   /*                                                                     */ 
 /*  A field can have multiple validation-types for example             */
 /*  e-mail is both e-mail and two fields alike that would look         */
 /*  like this: CampaignForm.Validate.Fields['example'] = '3,4[email]'  */
 /*                                                                     */
  /***********************************************************************/
 // Set which fields should be checked
 // Firstname
  CampaignForm.Validate.Fields['firstname'] = {
  Types: 'Any',
  ErrorMsg: ['Du m\xE5ste ange ett f\xF6rnamn']
  };
 
 // Lastname
  CampaignForm.Validate.Fields['lastname'] = {
  Types: 'Any',
  ErrorMsg: ['Du m\xE5ste ange ett efternamn']
  };
 
 // CO
  CampaignForm.Validate.Fields['co-address'] = {
  Types: 'XX',
  ErrorMsg: ['']
  };
 
 // Address
  CampaignForm.Validate.Fields['address'] = {
  Types: 'Any',
  ErrorMsg: ['Du m\xE5ste ange en adress']
  };
 
 // ZIP
  CampaignForm.Validate.Fields['zipcode'] = {
  Types: 'ZIP',
  ErrorMsg: ['Du m\xE5ste ange ett korrekt postnummer']
  };  
 
 // Locality
  CampaignForm.Validate.Fields['locality'] = {
  Types: 'Any',
  ErrorMsg: ['Du m\xE5ste ange en postort']
  };         
 // Phonenumber 
  CampaignForm.Validate.Fields['phone'] = {
  Types: 'Num',
  ErrorMsg: ['Du m\xE5ste ange ett korrekt telefonnummer']
  };
 
 // E-mail 1 
  CampaignForm.Validate.Fields['email'] = {
  Types: 'Mail',
  ErrorMsg: ['Du m\xE5ste ange en korrekt e-postadress']
  };
 
 // E-mail 2
  CampaignForm.Validate.Fields['email2'] = {
  Types: 'Match[email]',
  ErrorMsg: [
   'Dina e-postadresser matchar inte varandra'
  ]
  };
 
 // Appartment number
  CampaignForm.Validate.Fields['apartmentNr'] = {
  Types: 'XX',
  ErrorMsg: ['']
  };
 
 // Social security number
  CampaignForm.Validate.Fields['datebirth'] = {
  Types: 'PN',
  ErrorMsg: ['Du m\xE5ste ange ett korrekt personnummer']
  };
 
 // Conditions
  CampaignForm.Validate.Fields['agreements'] = {
  Types: 'CB',
  ErrorMsg: ['Du m\xE5ste acceptera villkoren f\xF6r k\xF6p']
  };
 
 // M8 channels
 if( $('#campaign_channellist').is('div') ) {
   CampaignForm.Validate.Fields['campaign_channellist'] = {
   Types: 'M8',
   ErrorMsg: ['Du m\xE5ste v\xE4lja minst \xE5tta tv-kanaler']
   };
  }
  // Bind validation-event to inputs
  $.each(CampaignForm.Validate.Fields, function(key, value){
  // But not if they're checkboxes, radiobtns or M8
   if( value.Types != 'CB' && value.Types != 'RB' && value.Types != 'M8'  ) {
     $('#'+key).bind(
     'focus', CampaignForm.Validate.Start
     );
     $('#'+key).bind(
      'blur', CampaignForm.Validate.Stop
     );
     CampaignForm.Validate.Fields[key].HasIcon = false;  
  } else if( value.Types == 'M8' ) {
    $('#' + key + ' input:not(.included)').click(
    function() {
     CampaignForm.Validate.Check('campaign_channellist', false, true);
    }
    ); 
  }
  });
  // Bind the onSubmit event to the form
  $('#campaign_form').submit(
   function() {
    return CampaignForm.Validate.CheckB4Send();
   }
  );
  
 },
 AddIcns : function(FieldId) {
  if( FieldId == 'zipcode' || FieldId == 'locality' ) {
   // Special solution zipcode and locality since they
   // are on the same row they share the icon
   var C = $('#'+FieldId).parents('div.campaign_flds:first');
   if( !$(C).find('span.campaign_input_valid:first').is('span') ) {
    $(C).append('<span class="campaign_input_valid"></span>');
   }
  } else {
  $('#'+FieldId).after('<span class="campaign_input_valid"></span>');
  }
 },
  Start : function() {
 CampaignForm.Validate.Timer = setTimeout(
  'CampaignForm.Validate.Check("'+this.id+'")', 100
 );
 },
 Stop : function() {
  clearTimeout(CampaignForm.Validate.Timer);
  CampaignForm.Validate.Timer = false;
 },
 CheckB4Send : function() {
 var Valid = true;
 $.each(CampaignForm.Validate.Fields, function(key, value) {
  if(!CampaignForm.Validate.Check(key, true)) {
 Valid = false;
   return false;
  }
 });
 if( Valid ) {
  // Before we send it we have to make sure that all
  // fields that we've hidden from the user are unchecked
var toUncheck = '#campaign_form fieldset.campaign_product_list ';
toUncheck+= '.campaign_expandable, ';
toUncheck+= '#campaign_form div.campaign_product_area';
  $(toUncheck).each(function(i) {
   // We check all DIVs that are expandable if they are hidden...
   if( $(this).css('display') == 'none' ) {
    // ...if they are we uncheck all radiobuttons and checkboxes in them
    $(this).find('input:checked').removeAttr('checked');
   }
  });
 
  // And the we also have to uncheck radiobuttons and checkboxes
  // which are children to checkboxes that are unchecked
  toUncheck = '#campaign_form label.campaign_product input:checkbox:not(:checked)';
  $(toUncheck).each(function(i) {
   p = $(this).parents('div.campaign_product:first');
   r = $(p).find('input:checked').removeAttr('checked');
  });
 
  // Lets send it!
  return true;
 } else {
  // Oops, it's not valid. We wont send it
  return false;
 }
 },
 Check : function(FieldId, BeforeSend, CheckOnce) {
  var Field = $('#'+FieldId);
  if( $(Field).is('input') ) {
  var FieldValue = $(Field).val();
  } else {
   var FieldValue = '';
 }
 
  var Types = CampaignForm.Validate.Fields[FieldId].Types;
  Types = Types.split(',');
  var Valid = true;
  var Error = false;
  var ErrorMsg = false;
  $.each(Types, function(i){
   Type = Types[i];
  
  
   // Check to see if should display the valid/unvalid icon
   // We dont want to display it before the user have started typing
   if( ( FieldValue != '' || BeforeSend )
       && !CampaignForm.Validate.Fields[FieldId].HasIcon
       && Type != 'CB' && Type != 'RB' && Type != 'M8' ) {
    CampaignForm.Validate.AddIcns(FieldId);
    CampaignForm.Validate.Fields[FieldId].HasIcon = true;
   }
  
   if( Type == 'Any' ) {
  
    // Check for anything
    if( FieldValue == '' ) {
   Valid = false;
    }
   } else if( Type == 'Num' ) {
  
    // Check for numbers only (allow - and space)
    var regExp = /^[\d\s-]+$/;
    if( FieldValue.search(regExp) == -1 ) {
   Valid = false;
    }
   } else if( Type == 'Mail' ) {
  
    // Check for an e-mailaddress
    var regExp = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if( FieldValue.search(regExp) == -1 ) {
   Valid = false;
    }   
   } else if( Type.indexOf('Match') != -1 ) {
  
    // Check for match in another field
    var F2Match = Types[i].substring(6, Types[i].length-1);
  var V2Match = $('#'+F2Match).val();
    if( FieldValue != V2Match && V2Match != '' ) {
   Valid = false;
    }   
   } else if( Type == 'PN' ) {
  
    // Check for social-security number (YYMMDD-XXXX)
    if( !CampaignForm.Validate.validatePNum(FieldValue) ) {
     Valid = false;
    }
      
   } else if( Type == 'XX' ) {
  
    // Field can contain anything or nothing
    Valid = true;
    return false;
   } else if( Type == 'CB' ) {
  
    // Checkbox should be checked
    if( !$('#' + FieldId).is(':checked') ) {
     Valid = false;
    }
   } else if( Type == 'ZIP' ) {
  
    // Check for zip-code (XXXXX || XXX XX)
    var regExp = /^([0-9]{5}$)|([0-9]{3}\s[0-9]{2}$)/;
    if( FieldValue.search(regExp) == -1 ) {
   Valid = false;
    }   
   } else if( Type == 'M8' ) {
  
   // Validate
   var jTxt = '#' + FieldId;
   jTxt+= ' input:checked:not(.included)';
   var cc = $(jTxt);
   if( cc.length != 8 ) {
    Valid = false;
    jTxt = '#' + FieldId;
    jTxt+= ' input:not(.included)';
    $(jTxt).removeAttr('disabled');
   } else {
    jTxt = '#' + FieldId;
    jTxt+= ' input:not(:checked)';
    $(jTxt).attr('disabled','disabled');
   }
   }
  
   // Break if not valid
   if( !Valid ) {
  ErrorMsg = CampaignForm.Validate.Fields[FieldId].ErrorMsg[i];
    return false;  
   }
  });
  if( !Valid ) {
   // Handle unvalid if not checkbox, radiobox or M8 (no icons for them)
   if( Type != 'CB' && Type != 'RB' && Type != 'M8' ) {
  
    // Display correct icon,once again special solution for zipcode and locality
    if( FieldId == 'zipcode' || FieldId == 'locality') {
     var I = $('#'+FieldId).parents('div.campaign_flds:first');
         I = $(I).find('span.campaign_input_valid:first');
    } else {
     var I = $('#'+FieldId).nextAll('span.campaign_input_valid:first');  
    }
    if( !$(I).hasClass('campaign_input_invalid') ) {
     $(I).addClass('campaign_input_invalid');
    }
       
   }
   if( BeforeSend ) {
   // Display alert
   if( $('#campaign_alert').is('div') ) {
    $('#campaign_alert').remove();
   }
   var aHTML = '<div id="campaign_alert">';
   aHTML+= '<div><p>';
   aHTML+= ErrorMsg;
   aHTML+= '</p></div>';     
   $('#campaign_form').append(aHTML);
   $('#campaign_alert').click(function() {
    $('#campaign_alert').remove();
   });
   return false;
  
   }
  } else {
 
   // Handle unvalid if not checkbox, radiobox or M8 (no icons for them)
   if( Type != 'CB' && Type != 'RB' && Type != 'M8' ) {
  
    // Display correct icon,once again special solution for zipcode and locality
    if( FieldId == 'zipcode' || FieldId == 'locality') {
     var I = $('#'+FieldId).parents('div.campaign_flds:first');
         I = $(I).find('span.campaign_input_valid:first');
    } else {
     var I = $('#'+FieldId).nextAll('span.campaign_input_valid:first');  
    }
    if( $(I).hasClass('campaign_input_invalid') ) {
     $(I).removeClass('campaign_input_invalid');
    }
   }
   if( BeforeSend ) { return true; }   
  }
 
  if(!BeforeSend  && !CheckOnce) {
   CampaignForm.Validate.Timer = setTimeout(
   'CampaignForm.Validate.Check("'+FieldId+'")', 100
  ); 
  }
 
 },
  validatePNum :function(sPNum) {
   sPNum=sPNum.replace("-", "")
   if( sPNum.length == 10 ) {
   sPNum = '19' + sPNum;
   }
   var numbers = sPNum.match(/^(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)$/);
   var checkSum = 0;
   var d = new Date();
   if(!CampaignForm.Validate.isDate(sPNum.substring(0,4),sPNum.substring(4,6),sPNum.substring(6,8))) {
     return false;
   }
   if (numbers == null) { return false; }
   var n;
   for (var i = 3; i <= 12; i++) {
    n=parseInt(numbers[i]);
    if (i % 2 == 0) {
     checkSum+=n;
    } else {
     checkSum+=(n*2)%9+Math.floor(n/9)*9
    }
   }
   if( checkSum%10==0) { return true; }
   return false;
  },
 
getYear : function(y) { return (y < 1000) ? y + 1900 : y; },
isDate : function(year, month, day) {
 month = month - 1; // 0-11 in JavaScript
   var tmpDate = new Date(year,month,day);
   if ( (CampaignForm.Validate.getYear(tmpDate.getYear()) == year) &&
   (month == tmpDate.getMonth()) &&
   (day == tmpDate.getDate()) )
    return true;
   else
    return false;
}
 },
 // Lightboxes
 LB : {
 
  Init : function() {
   $('#campaign_form .campaign_lb_c').hide();
   $('#campaign_form a.campaign_lightbox').each(
   function(i) {
    var id = this.href;
    id = id.split('#');
    id = id[1];
    $(this).click(function() {
     CampaignForm.LB.Show(id, $(this));
    });
    $(this).removeAttr('href');
    $(this).css('cursor','pointer');
   }
   );
  
  },
 
  Show : function(id, obj) {
 if( !( $.browser.msie && $.browser.version.indexOf('6.0') != -1 ) ) {
 $('body').append('<div id="campaign_lights_out"></div>');
 $('#campaign_lights_out').height( $(document).height() );
 }
  
   HTML = '<div class="campaign_lb" id="campaign_lb_form">';
   HTML+= '<div class="campaign_lb_content">';
   HTML+= $('#'+id).html();
   HTML+= '</div></div>';
   $('body').append(HTML);
   
   $('#campaign_lb_form').append(
    '<span class="campaign_close"></span>'
   );
   $('#campaign_lb_form span.campaign_close').click(
    CampaignForm.LB.Close
   );
  
   // IE6 can't handle position fixed
   if( $.browser.msie && $.browser.version.indexOf('6.0') != -1 ) {
   o = $(obj).offset();
   $('#campaign_lb_form').css({
    position: 'absolute',
  top: ( o.top - 100 ) + 'px'
   });
   }
  
   $('#campaign_lb_form').slideDown(500);  
  },
 
  Close : function() {
   $('#campaign_lb_form').slideUp(500, function() {
    $('#campaign_lights_out, #campaign_lb_form').remove();
   })
  }
 },
 // Popup script froms scripts.js
 showInfoPopUp: function(serviceId) {
 url = "?serviceId=" + serviceId;
 window.open('http://www.comhem.se/portlets/popUp/popup.jsp'+url,'icMonthlyFee','toolbar=0,location=no,directories=0,status=1,menubar=0,scrollbars=1,resizable=no,width=340,height=500');
 }
}