// JavaScript Document

function clearBox(box){
if (box.value=="טלפון סלולארי") box.value = "";
box.focus();
}

function AcceptDigits(objtextbox)
{
var exp = /[^\d]/g;
objtextbox.value = objtextbox.value.replace(exp,'');
}


/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
 
 //programs = [37,35,40];
 //var selected_program = 28;
 var old_circle;
 var last_circle;

 function mycarousel_itemFirstInCallback(carousel,c,f){
	 jQuery('#current_book')[0].innerHTML = (f);
	 selected_program = programs[f+ chosen_offset];

  if (f==(carousel.options.size-2)){
	  carousel.buttonNext.hide();
	  jQuery('#mycarousel-next')[0].style.visibility = "hidden";
 }else{
	   carousel.buttonNext.show();
	   jQuery('#mycarousel-next')[0].style.visibility = "visible"; }
  if (f==1){
	  jQuery('#mycarousel-prev')[0].style.visibility = "hidden";
 }else{
	   jQuery('#mycarousel-prev')[0].style.visibility = "visible"; }

  if(last_circle) last_circle.className="circle";
  t = jQuery('.jcarousel-control #' + f)[0];
  if (t){t.className="circle_f";
  last_circle= t;
 }
 }
 

 
 function mycarousel_buttonNextCallback(carousel,c,f){
	alert("mycarousel_buttonNextCallback");
 	 }

 function mycarousel_buttonPrevCallback(carousel,c,f){
 	alert("mycarousel_buttonPrevCallback");
 }
 
function make_circles(){
	str = "";

     for (i=0;i<(programs).length;i++){
		str += '<a class="circle"  href="#" id="' + (i+1) + '"></a>'
	}

    jQuery('#control_circles')[0].innerHTML = str;
}

function mycarousel_initCallback(carousel) {
	
    make_circles();
    jQuery('.jcarousel-control a').bind('click', function() {

        carousel.scroll(jQuery.jcarousel.intval(jQuery(this)[0].id));
        return false;
    });

    jQuery('#wrap .bookItem a').bind('click', function() {

        carousel.scroll(jQuery.jcarousel.intval(jQuery(this)[0].id));
        return false;
    });


    jQuery('#mycarousel-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#mycarousel-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
	
	
};

// Ride the carousel...
jQuery(document).ready(function() {
    jQuery("#mycarousel").jcarousel({
        scroll: 1,
		start:jcarousel_start,
		initCallback: mycarousel_initCallback,
		/*buttonNextCallback: mycarousel_buttonNextCallback,
		buttonPrevCallback: mycarousel_buttonPrevCallback,*/
		itemFirstInCallback:mycarousel_itemFirstInCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
		
    });
	


});

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function subscribe(){
	jQuery("#subscribeBtn")[0].value = "המתן";
	jQuery("#subscribeBtn")[0].disabled= true;
	phone = jQuery("#phonenumber")[0].value;


       aff = getQuerystring('aff',defaultAff);
       subaff = getQuerystring('subaff');
	
	if (checkNumber(phone)){
		$.getJSON("/api/subscribe/" + selected_program + "/?phone_number="+ phone + "&application=0" + "&aff=" + aff + "&subaff=" + subaff,

			function(data){
					jQuery("#subscribeBtn")[0].value = "שלח";
					jQuery("#subscribeBtn")[0].disabled= false;;
				//console.dir(data);
				if (data.success == true) {
					new Dialog({title:"הזן קוד",
								content: 'ברגעים אלו נשלח SMS למכשירך עם קוד אישי אנא הזן אותו כעת<br /><input size="4" maxlength="4" type="text" onkeyup="AcceptDigits(this)" id="prompt-input" /> לא קיבלתי <a href="javascript:resend()">שלח שוב</a> <div><label><input type="checkbox" id="accept"/> אני מקבל את <a href="/terms/">תנאי ההרשמה</a></label></div><div id="prompt-error"></div>',
								focus: 'prompt-input',
								buttons: {
										'המשך': function() {
											var accept = document.getElementById('accept').checked;
											
											var inputText = document.getElementById('prompt-input').value;
											if (accept == false){
												document.getElementById('prompt-error').innerHTML = ('עלייך לקבל את תנאי ההרשמה');
											}
											else{
												if (inputText.length > 0) {
													///
													dialogBox = this;
													validate(inputText,this)
													document.getElementById('prompt-error').innerHTML = ('אנא המתן');	
													
												} else {
													document.getElementById('prompt-error').innerHTML = ('לא הוזן קוד');
												}
											}
										},
										'בטל': Dialog.prototype.close
									}
						});
				}
				else{
				//alert(data.message);
				new Dialog({content: data.message});
				}
			});
	}
	else{
		jQuery("#subscribeBtn")[0].value = "שלח";
		jQuery("#subscribeBtn")[0].disabled= false;;
			new Dialog({title:"שגיאה",
						    content: 'מספר הטלפון לא חוקי'
							}
					);
	}
	

}


function validate(code,dialog){
	phone = jQuery("#phonenumber")[0].value;
	$.getJSON("/api/validate/" + selected_program + "/?phone_number="+ phone + "&pin=" + code,
        function(data){
			
			if (data.success == true) {
				sendPixel(phone);
				new Dialog({title:"ברוך הבא",
						    content: 'תודה על ההרשמה! מיד תקבל את הפרק הראשון בספר '
							}
					);
				//sendPixel(phone);
				dialog.close();
			}
			else{
				document.getElementById('prompt-error').innerHTML = ('קוד שגוי, נסה שנית');
			//alert(data.message);
			//new Dialog({content: data.message});
			}
        });	
	
	
}
function resend(){
	phone = jQuery("#phonenumber")[0].value;
	$.getJSON("/api/resend/" + selected_program + "/?phone_number="+ phone,
        function(data){
			
			if (data.success == true) {
				//
			}
			else{
				//document.getElementById('prompt-error').innerHTML = ('קוד שגוי, נסה שנית');
			}
        });	
	
	
}
function checkNumber(phone){
	if(( phone.length <10) || (isNaN(phone))){		
		return false;
	}
	if(phone.substring(0,2)!="05"){		
		return false;
	}
	return true;
	
	
	
}


function sendPixel(phone){
	//console.info("sendPixel");
       var aff = getQuerystring('aff','24');
	//console.info("aff");
	var url = "/api/optimization_pixel/" + aff + "/" + selected_program + "/" + phone + "/test";
	//console.info(url);
	$.getJSON(url,
		   function(data){
			//console.dir(data);
			
			if (data.success == true) {
				//console.info(data);
				jQuery("#iframe")[0].innerHTML = data.pixel;
				//console.dir(jQuery("#iframe")[0]);
				//eval(data.pixel);
			}
			else{
				//console.error("couldn't send pixel");
			}
        });

}

window.onresize =function(event) {
var winW = 630, winH = 460;

if (parseInt(navigator.appVersion)>3) {
 if (navigator.appName=="Netscape") {
  winW = window.innerWidth;
  winH = window.innerHeight;
 }
 if (navigator.appName.indexOf("Microsoft")!=-1) {
  winW = document.body.offsetWidth;
  winH = document.body.offsetHeight;
 }
 if (winW <1275){
  jQuery("#leaf img").hide();
 }
 else{
 jQuery("#leaf img").show();
 }
 console.info(winW);
}


}