﻿///////////////////////////////////////////////////////////////////////////
// Run on load
///////////////////////////////////////////////////////////////////////////
WritePopupDivToPage(); // Write sms code popup to page

///////////////////////////////////////////////////////////////////////////
// Global variables
///////////////////////////////////////////////////////////////////////////

var previousPreview = null; // The last preview object
var currentPreview = null; // The current preview object
var goBackToStepFour = false; // Flag that indicates if there is a need to go back to step 4 from the currrent step (for Graphics (MMS) preview)
var isHarshLoggedIn = false; // Is user harsh loggedin (Then there is no need to send him harsh code)

///////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////
// CurrentPreviewObj Class
///////////////////////////////////////////////////////////////////////////

function CurrentPreviewObj(PreviewStep1ID, PreviewStep2ID, PreviewStep3ID, PreviewStep4ID, PreviewStep5ID, ActivePlayerID, MessageLableID, SendOneTimePasswordLableID, MsisdnTextID, VideoImgPnlID, VideoFilePath, TermsChbID, HarshCodeTextID, MediaType)
{
    // Object members
    this.currentPreviewStep1 = document.getElementById(PreviewStep1ID);
    this.currentPreviewStep2 = document.getElementById(PreviewStep2ID);
    this.currentPreviewStep3 = document.getElementById(PreviewStep3ID);
    this.currentPreviewStep4 = document.getElementById(PreviewStep4ID);
    this.currentPreviewStep5 = document.getElementById(PreviewStep5ID);
    this.currentActivePlayer = document.getElementById(ActivePlayerID);
    this.currentMessageLable = document.getElementById(MessageLableID);
    this.currentSendOneTimePasswordLable = document.getElementById(SendOneTimePasswordLableID);
    this.currentMsisdnText = document.getElementById(MsisdnTextID);
    this.currentVideoImgPnl = document.getElementById(VideoImgPnlID);
    this.currentTermsChb = document.getElementById(TermsChbID);
    this.currentHarshCodeText = document.getElementById(HarshCodeTextID);
    this.currentVideoFilePath = VideoFilePath;
    this.controlMediaType = MediaType;
    this.bufferImage = null;
    
    // Object methods
    this.ShowStepOne = ShowStepOne;
    this.ShowStepTwo = ShowStepTwo;
    this.ShowStepThree = ShowStepThree;
    this.ShowStepFour = ShowStepFour;
    this.ShowStepFive = ShowStepFive;
    this.StopAudio = StopAudio;
    this.StopVideo = StopVideo;
    this.PlayAudio = PlayAudio;
    this.PlayVideo = PlayVideo;
    this.Equals = Equals;
    this.ResetAudio = ResetAudio;
    this.ResetVideo = ResetVideo;
    this.ResetGraphics = ResetGraphics;
    this.DownloadSoundLoggedIn = DownloadSoundLoggedIn;
    this.DownloadSoundNotLoggedIn = DownloadSoundNotLoggedIn;
    this.DownloadClipLoggedIn = DownloadClipLoggedIn;
    this.DownloadClipNotLoggedIn = DownloadClipNotLoggedIn;
    this.DownloadGraphicsLoggedIn = DownloadGraphicsLoggedIn;
    this.DownloadGraphicsNotLoggedIn = DownloadGraphicsNotLoggedIn;
    this.ClearText = ClearText;
    this.IsStep2displayed = IsStep2displayed;
    this.RestoreVideoImage = RestoreVideoImage;
    this.SendOneTimePassword = SendOneTimePassword;
    this.SendItem = SendItem;
    this.StopPlayingMediaType = StopPlayingMediaType;
}

/************************************************
 * CurrentPreviewObj class methods implementation
 ************************************************/
 
////////////////////////////////////////////////////////
/// Stops playing video/audio according to media type
////////////////////////////////////////////////////////
function StopPlayingMediaType()
{
    switch(this.controlMediaType)
    {
        case 'Audio' : 
            this.ResetAudio();
            break;
        case 'Video' : 
            this.ResetVideo();
            break;
    }
}

////////////////////////////////////////////////////////
/// Finds out if two CurrentPreviewObj objects are equal
////////////////////////////////////////////////////////
function Equals(Obj)
{
    // All objects has steps 1,2,3 only Graphics (MMS) has steps 4,5
    return this.currentPreviewStep1 == Obj.currentPreviewStep1 &&
           this.currentPreviewStep2 == Obj.currentPreviewStep2 &&
           this.currentPreviewStep3 == Obj.currentPreviewStep3;
}

/////////////////////////////////////////////////////////////////////////
/// Shows step 1 of current CurrentPreviewObj object, hides rest of steps
/////////////////////////////////////////////////////////////////////////
function ShowStepOne()
{
    // Steps 4,5 only for Graphics (MMS)
    if(this.currentPreviewStep5 != null)this.currentPreviewStep5.style.display = "none";
    if(this.currentPreviewStep4 != null)this.currentPreviewStep4.style.display = "none";
    this.currentPreviewStep3.style.display = "none";
    this.currentPreviewStep2.style.display = "none";
    this.currentPreviewStep1.style.display = "";
}

/////////////////////////////////////////////////////////////////////////
/// Shows step 2 of current CurrentPreviewObj object, hides rest of steps
/////////////////////////////////////////////////////////////////////////
function ShowStepTwo()
{



var cookieVal = ReadCookie("msisdn");

if (cookieVal != "" && cookieVal != ";" )
{ 
   document.getElementById(this.currentMsisdnText.id).value= cookieVal;
}

    // Steps 4,5 only for Graphics (MMS)
    if(this.currentPreviewStep5 != null)this.currentPreviewStep5.style.display = "none";
    if(this.currentPreviewStep4 != null)this.currentPreviewStep4.style.display = "none";
    this.currentPreviewStep3.style.display = "none";
    this.currentPreviewStep2.style.display = "";
    this.currentPreviewStep1.style.display = "none";
    this.currentMsisdnText.focus(); // Focus on MSISDN text box
}

/////////////////////////////////////////////////////////////////////////
/// Shows step 3 of current CurrentPreviewObj object, hides rest of steps
/////////////////////////////////////////////////////////////////////////
function ShowStepThree()
{
    // Steps 4,5 only for Graphics (MMS)
    if(this.currentPreviewStep5 != null)this.currentPreviewStep5.style.display = "none";
    if(this.currentPreviewStep4 != null)this.currentPreviewStep4.style.display = "none";
    this.currentPreviewStep3.style.display = "";
    this.currentPreviewStep2.style.display = "none";
    this.currentPreviewStep1.style.display = "none";
}

/////////////////////////////////////////////////////////////////////////
/// Shows step 4 of current CurrentPreviewObj object, hides rest of steps
/////////////////////////////////////////////////////////////////////////
function ShowStepFour()
{
    // Only Graphics (MMS) uses this method, there for there is no check if steps 4,5 are null
    this.currentPreviewStep5.style.display = "none";
    this.currentPreviewStep4.style.display = "";
    this.currentPreviewStep3.style.display = "none";
    this.currentPreviewStep2.style.display = "none";
    this.currentPreviewStep1.style.display = "none";
    this.currentHarshCodeText.focus(); // Focus on HarshCode text box
}

/////////////////////////////////////////////////////////////////////////
/// Shows step 5 of current CurrentPreviewObj object, hides rest of steps
/////////////////////////////////////////////////////////////////////////
function ShowStepFive()
{
    // Only Graphics (MMS) uses this method, there for there is no check if steps 4,5 are null
    this.currentPreviewStep5.style.display = "";
    this.currentPreviewStep4.style.display = "none";
    this.currentPreviewStep3.style.display = "none";
    this.currentPreviewStep2.style.display = "none";
    this.currentPreviewStep1.style.display = "none";
}

/////////////////////////////////////////////
/// Resest the Audio CurrentPreviewObj object
/////////////////////////////////////////////
function ResetAudio()
{
    this.StopAudio();
    this.ShowStepOne();
}

/////////////////////////////////////////////
/// Resest the Vedio CurrentPreviewObj object
/////////////////////////////////////////////
function ResetVideo()
{
    this.StopVideo();
    this.ShowStepOne();
}

////////////////////////////////////////////////
/// Resest the Graphics CurrentPreviewObj object
////////////////////////////////////////////////
function ResetGraphics()
{
    this.ShowStepOne();
}

///////////////////////////////////////////////////////////////////////////////
/// Restores the Video CurrentPreviewObj object image, when the video is stoped
///////////////////////////////////////////////////////////////////////////////
function RestoreVideoImage()
{
    if(this.bufferImage != null) // If the current CurrentPreviewObj object image html (<img ....) was saved before starting to play the video
    {
        this.currentVideoImgPnl.innerHTML = this.bufferImage; // Restore the image and stop playing video
        this.bufferImage = null;
    }
    else // If the current CurrentPreviewObj object image html (<img ....) was not saved
    {
        // Try to restore the previews CurrentPreviewObj object image html
        if(previousPreview.bufferImage != null)
            previousPreview.RestoreVideoImage();
    }
}

////////////////////////////////////////////////////////////////////////////
/// Finds out if the CurrentPreviewObj object step 2 is currentlly displayed
////////////////////////////////////////////////////////////////////////////
function IsStep2displayed()
{
    return this.currentPreviewStep2.style.display == "";
}

///////////////////////////////////////////////////////
/// Clears the CurrentPreviewObj object MSISDN text box
///////////////////////////////////////////////////////
function ClearText()
{
    this.currentMsisdnText.value = "";
}

///////////////////////////////////////////////////////
/// Stops the Audio CurrentPreviewObj object audio play
///////////////////////////////////////////////////////
function StopAudio()
{
	var player = document.getElementById('player'); // Find the player
	
	if(player != null) // If posible, reset the player
	    player.innerHTML = "";
	    
	if(this.currentActivePlayer != null) // If posible, change the Audio CurrentPreviewObj object's play button style
	    this.currentActivePlayer.className = "ringtone_icon";
}

/////////////////////////////////////////////////////////////
/// Plays (or stops) the Audio CurrentPreviewObj object audio
/////////////////////////////////////////////////////////////
function PlayAudio(cpid, apid, LanguageId)
{
    if(this.currentActivePlayer != null) // If the Audio CurrentPreviewObj object's play button exists
    {
	    if(this.currentActivePlayer.className == "ringtone_icon") // If the Audio CurrentPreviewObj object's play button's style is set to not playing, then start playing
	    {//play
		    path = GetFromMPower(cpid, apid, LanguageId); // Get the audio file path

        //alert(path);

		    this.currentActivePlayer.className = "ringtone_icon_play"; // Set the Audio CurrentPreviewObj object's play button's style to play
		    
		    var player = document.getElementById('player'); // Get the player
		    if(player != null) // If the player exist
		        player.innerHTML = GetAudioPlayer(path); // Start playing audio
	    }
	    else // If the Audio CurrentPreviewObj object's play button's style is set to playing, then stop playing
	    {//stop
		    this.StopAudio(); // Stop Audio CurrentPreviewObj object's play 
	    }
	}
}

/////////////////////////////////////////////////////////////
/// Plays (or stops) the Video CurrentPreviewObj object video
/////////////////////////////////////////////////////////////
function PlayVideo()
{	
    if(this.currentActivePlayer != null) // If the Video CurrentPreviewObj object's play button exists
    {
        // If the Video CurrentPreviewObj object's play button's style is set to not playing, then start playing
	    if(this.currentActivePlayer.className == 'vplaybtn' || this.currentActivePlayer.className == 'vplaybtnhover')
	    {//play
	        this.bufferImage = this.currentVideoImgPnl.innerHTML; // Save the Video CurrentPreviewObj object image html (<img ....) 
	        this.currentActivePlayer.className = "vstopbtn"; // Set the Video CurrentPreviewObj object's play button's style to play
	        this.currentVideoImgPnl.innerHTML = GetVideoPlayer(this.currentVideoFilePath); // Start playing video
	    }
	    else // If the Video CurrentPreviewObj object's play button's style is set to playing, then stop playing
	    {//stop
		    this.StopVideo(); // Stop Video CurrentPreviewObj object's play 
		}
	}
}

///////////////////////////////////////////////////////
/// Stops the Video CurrentPreviewObj object video play
///////////////////////////////////////////////////////
function StopVideo()
{    
    // If posible set the Video CurrentPreviewObj object's play button's style to stop
	if(this.currentActivePlayer != null)
	    this.currentActivePlayer.className = "vplaybtn";
	    
	this.RestoreVideoImage(); // Restor the video image and stop playing the video
}

/////////////////////////////////////////////////////////////////
/// Download the audio item to the user's mobile in loggedin mode
/////////////////////////////////////////////////////////////////
function DownloadSoundLoggedIn(cpid, apid, LanguageId)
{
    // If posible, reset the previous Audio CurrentPreviewObj object (stop playing and go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetAudio()
    
    this.SendItem(cpid, apid, null, LanguageId); // Send item
}

/////////////////////////////////////////////////////////////////////
/// Download the audio item to the user's mobile in not loggedin mode
/////////////////////////////////////////////////////////////////////
function DownloadSoundNotLoggedIn(cpid, apid, msisdn, LanguageId)
{
    // If posible, reset the previous Audio CurrentPreviewObj object (stop playing and go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetAudio();

    this.SendItem(cpid, apid, msisdn, LanguageId); // Send item
}

/////////////////////////////////////////////////////////////////
/// Download the video item to the user's mobile in loggedin mode
/////////////////////////////////////////////////////////////////
function DownloadClipLoggedIn(cpid, apid, LanguageId)
{
    // If posible, reset the previous Video CurrentPreviewObj object (stop playing and go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetVideo()
    
    this.SendItem(cpid, apid, null, LanguageId); // Send item
}

/////////////////////////////////////////////////////////////////////
/// Download the video item to the user's mobile in not loggedin mode
/////////////////////////////////////////////////////////////////////
function DownloadClipNotLoggedIn(cpid, apid, msisdn, LanguageId)
{
    // If posible, reset the previous Video CurrentPreviewObj object (stop playing and go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetVideo();

    this.SendItem(cpid, apid, msisdn, LanguageId); // Send item
}

////////////////////////////////////////////////////////////////////
/// Download the graphics item to the user's mobile in loggedin mode
////////////////////////////////////////////////////////////////////
function DownloadGraphicsLoggedIn(cpid, apid, LanguageId)
{
    // If posible, reset the previous Graphics CurrentPreviewObj object (go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetGraphics()
    
    this.SendItem(cpid, apid, null, LanguageId); // Send item
}

////////////////////////////////////////////////////////////////////////
/// Download the graphics item to the user's mobile in not loggedin mode
////////////////////////////////////////////////////////////////////////
function DownloadGraphicsNotLoggedIn(cpid, apid, msisdn, LanguageId)
{
    // If posible, reset the previous Graphics CurrentPreviewObj object (go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetGraphics();
        
    this.SendItem(cpid, apid, msisdn, LanguageId); // Send item
}

////////////////////////////////////////////////////////
/// Sends a harsh code to user (for Graphics (MMS) only)
////////////////////////////////////////////////////////
function SendOneTimePassword(msisdn, isFirstTime)
{
    // If posible, reset the previous Graphics CurrentPreviewObj object (go to step 1)
    if(previousPreview != null && !previousPreview.Equals(this))
        previousPreview.ResetGraphics();

    var returnMessage = "";

    returnMessage = ServerRequestSendHarshCode(msisdn); // Sent the harsh code
    if(isFirstTime) // If this is the first time the code is sent
    {
        if(returnMessage != "") // If the returned message is not empty string (problem sending harsh code)
        {
            this.currentMessageLable.innerText = returnMessage; // Set message
            this.ShowStepThree(); // Show message (step 3)
        }
        else // If the returned message is an empty string (then everything is o.k.)
        {
            this.currentHarshCodeText.value = ""; // Reset the text box where the user need to enter the harsh code that was sent
            this.ShowStepFour(); // Let the user enter the harsh code that was sent to him (step 4)
        }
    }
    else // If this is not the first time the code is sent (The code was sent frop step 4, not step 1)
    {
        if(returnMessage == "") // If the returned message is an empty string (then everything is o.k.)
        {
            this.currentSendOneTimePasswordLable.innerText = "סיסמה נשלחה בהצלחה"; // Set message
            this.ShowStepFive(); // Show message (step 4 - message and continue button)
        }
        else // If the returned message is not empty string (problem sending harsh code)
        {
            this.currentMessageLable.innerText = returnMessage; // Set message
            this.ShowStepThree(); // Show message (step 3)
        }
    }
}

//////////////////////////////////
/// Sends an item to user's mobile
//////////////////////////////////
function SendItem(cpid, apid, msisdn, LanguageId)
{
    var returnMessage = "";

    returnMessage = ServerRequest(cpid, apid, msisdn, LanguageId); // Send the item
    if(  returnMessage == "over 3 times")
    {
        this.currentMessageLable.innerText = ""; // Set message
      //  if(currentPreview.currentPreviewStep3 != null)currentPreview.currentPreviewStep3.style.display = "none";
    }
    else
    this.currentMessageLable.innerText = returnMessage; // Set message

    this.ShowStepThree(); // Show message (step 3)
}

///////////////////////////////////////////////////////////////////////////



///////////////////////////////////////////////////////////////////////////
// Global methods
///////////////////////////////////////////////////////////////////////////


/***********************
 * Public global methods
 ***********************/

var offsetxpoint=-60 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(){
if (ns6||ie){
enabletip=true
return false
}
}

function positiontip(e){
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.display="inline";
}
}

function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.display="none"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}




////////////////////////
 /// Open sms code popup
 ////////////////////////
function OpenPopup(obj,e){
enabletip=true;
    document.getElementById("divSMSnum").innerHTML = obj; 
    positiontip(e);
}

 ////////////////////////
 /// Close sms code popup
 ////////////////////////
function ClosePopup(){
   hideddrivetip();
}

 
 
////////////////////////////////
/// Write sms code popup to page
////////////////////////////////
function WritePopupDivToPage()
{
  document.write("<span id='dhtmltooltip' class='getatlas' >   <span id='divSMSnum' ></span></span>");
  ddrivetip();
}
 
//////////////////////////////////////////////////////////
/// Sets the current and previous CurrentPreviewObj ojects
//////////////////////////////////////////////////////////
function SetCurrentPreview(PreviewStep1Id, PreviewStep2Id, PreviewStep3Id, PreviewStep4Id, PreviewStep5Id, ActivePlayerId, MessageLableId, SendOneTimePasswordLableId, MsisdnTextId, VideoImgPnlID, VideoFilePath, TermsChbId, HarshCodeTextId, MediaType)
{




    // Set previous object
    previousPreview = currentPreview; 
    // Set current object
    currentPreview = new CurrentPreviewObj(PreviewStep1Id, PreviewStep2Id, PreviewStep3Id, PreviewStep4Id, PreviewStep5Id, ActivePlayerId, MessageLableId, SendOneTimePasswordLableId, MsisdnTextId, VideoImgPnlID, VideoFilePath, TermsChbId, HarshCodeTextId, MediaType);
}

//////////////
/// Play audio
//////////////
function PlaySound(cpid, apid, LanguageId)
{
    // If posible reset previous audio CurrentPreviewObj oject
    if(previousPreview != null && !previousPreview.Equals(currentPreview))
        previousPreview.StopPlayingMediaType();
    currentPreview.PlayAudio(cpid, apid, LanguageId); // Play audio
}

//////////////
/// Play video
//////////////
function PlayClip()
{
    // If posible reset previous video CurrentPreviewObj oject
    if(previousPreview != null && !previousPreview.Equals(currentPreview))
        previousPreview.StopPlayingMediaType();
    currentPreview.PlayVideo(); // Play video
}

////////////////////////////////////////////
/// Download the audio item to user's mobile
////////////////////////////////////////////
function DownloadSound(cpid, apid, msisdn, LanguageId)
{
    if(currentPreview != null)
    {
        // If in step 2 then user is not logged in
        if(currentPreview.IsStep2displayed())
        {
            var tmpMsisdn = currentPreview.currentMsisdnText.value; // Get the MSISDN entered by the user
            if(IsMsisdnValid(tmpMsisdn)) // Check MSISDN validity
                currentPreview.DownloadSoundNotLoggedIn(cpid, apid, tmpMsisdn, LanguageId); // Download the item
        }
        else // In step 1, logged in or not
        {
            if(msisdn == "") // If not logged in, move to step 2
            {
                if(previousPreview != null) // If posible, reset previews Audio CurrentPreviewObj object
                    previousPreview.ResetAudio();
                currentPreview.ClearText(); // Clear the MSISDN text box
                currentPreview.ShowStepTwo(); // Show step 2
            }
            else // Logged in
            {
                currentPreview.DownloadSoundLoggedIn(cpid, apid, LanguageId); // Download the item
            }
        }
    }
}

////////////////////////////////////////////
/// Download the video item to user's mobile
////////////////////////////////////////////
function DownloadClip(cpid, apid, msisdn, LanguageId)
{
    if(currentPreview != null)
    {
        // If in step 2 then user is not logged in
        if(currentPreview.IsStep2displayed())
        {
            var tmpMsisdn = currentPreview.currentMsisdnText.value; // Get the MSISDN entered by the user
            if(IsMsisdnValid(tmpMsisdn)) // Check MSISDN validity
                currentPreview.DownloadClipNotLoggedIn(cpid, apid, tmpMsisdn, LanguageId); // Download the item
        }
        else // In step 1, logged in or not
        {
            if(msisdn == "") // If not logged in, move to step 2
            {
                if(previousPreview != null) // If posible, reset previews Video CurrentPreviewObj object
                    previousPreview.ResetVideo();
                currentPreview.ClearText(); // Clear the MSISDN text box
                currentPreview.ShowStepTwo(); // Show step 2
            }
            else // Logged in
            {
                currentPreview.DownloadClipLoggedIn(cpid, apid, LanguageId); // Download the item
            }
        }
    }
}

///////////////////////////////////////////////
/// Download the graphics item to user's mobile
///////////////////////////////////////////////
function DownloadGraphics(cpid, apid, msisdn, LanguageId)
{
    if(currentPreview != null)
    {
        // If user didn't checked the terms check box
        if(!currentPreview.currentTermsChb.checked)
        {
            currentPreview.currentMessageLable.innerText = "אנא אשר את תנאי השימוש"; // Set message
            goBackToStepFour = true; // After the user reads the message, return to step 4
            currentPreview.ShowStepThree(); // Show message (step three)
        }
        else // If user checked the terms check box
        {
            var result = "";
            if(!isHarshLoggedIn) // If the user is not harsh logged in
            {
                // Confirm the entered harsh code by the user against the sent harsh code
                result = ServerRequestConfirmHarshCode(currentPreview.currentHarshCodeText.value)
            }
            if(result != "") // If the returnd message is not an empty string (confirmation failed)
            {
                currentPreview.currentSendOneTimePasswordLable.innerText = result // Set message
                currentPreview.ShowStepFive(); // Show message (Step 5)
            }
            else // The confirmation succeeded, or user is harsh logged in
            {
                isHarshLoggedIn = true; // Remember the user is harsh logged in (if he wasn't)
                
                if(msisdn == "") // If not logged in
                {
                    var enteredMsisdn = currentPreview.currentMsisdnText.value; // Get the MSISDN entered by the user
                    if(enteredMsisdn == "") // If the user haven't entered MSISDN
                    {
                        currentPreview.ShowStepTwo(); // Let the user enter MSISDN (step 2)
                    }
                    else // If the user entered MSISDN
                    {
                        // Download item
                        if(IsMsisdnValid(enteredMsisdn)) // Check MSISDN validity
                            currentPreview.DownloadGraphicsNotLoggedIn(cpid, apid, enteredMsisdn, LanguageId);
                    }
                }
                else // If logged in
                {
                    // Download item
                    currentPreview.DownloadGraphicsLoggedIn(cpid, apid, LanguageId);
                }   
            }   
        }
    }
}

///////////////////////////////////////////////
/// Send the user harsh code for the first time
///////////////////////////////////////////////
function SendHarshCode(cpid, apid, msisdn , txtMsisdn)
{ 
 


    if(isHarshLoggedIn) // If user is harsh logged in
    {
        currentPreview.currentTermsChb.checked = true; // Set terms check box to true, so the check in method DownloadGraphics will pass
        
        if(currentPreview.IsStep2displayed()) // If in step 2 then user is not logged in
        {
            DownloadGraphics(cpid, apid, "");
        }
        else // logged in or not
        {
            if(msisdn == "") // If not logged in, move to step 2
            {
                // If posible, reset previews Graphics CurrentPreviewObj object
                if(previousPreview != null) 
                    previousPreview.ResetGraphics();
                currentPreview.ClearText(); // Clear the MSISDN text box
                currentPreview.ShowStepTwo(); // Show step 2
            }
            else // Logged in
            {
                DownloadGraphics(cpid, apid, msisdn); // Download the item
            }
        }
    }
    else // If user is not harsh logged in
    {
        if(currentPreview != null)
        {
            // If in step 2 then user is not logged in
            if(currentPreview.IsStep2displayed())
            {
                var tmpMsisdn = currentPreview.currentMsisdnText.value; // Get the MSISDN entered by the user
                if(IsMsisdnValid(tmpMsisdn)) // Check MSISDN validity
                {
                    var res = CheckMsisdnBalance(tmpMsisdn);
                    if( res == "over 3 times")
                    {
                         window.location.href = "Login.aspx";
                         if(currentPreview.currentPreviewStep3 != null)currentPreview.currentPreviewStep3.style.display = "none";
                    }
                    else
                    currentPreview.SendOneTimePassword(tmpMsisdn, true); // Send the user harsh code
                }
            }
            else // logged in or not
            {
                if(msisdn == "") // If not logged in, move to step 2
                {
                    // If posible, reset previews Graphics CurrentPreviewObj object
                    if(previousPreview != null)
                        previousPreview.ResetGraphics();
                    currentPreview.ClearText(); // Clear the MSISDN text box
                    currentPreview.ShowStepTwo(); // Show step 2
                }
                else // Logged in
                {
                    currentPreview.SendOneTimePassword("", true); // Send the user harsh code
                }
            }
        }
    }
}

///////////////////////////////////////////////
/// Send the user harsh code not the first time
///////////////////////////////////////////////
function SendHarshCodeAgain(msisdn)
{
    if(currentPreview != null)
    {
        if(msisdn != "") // If logged in
        {
            currentPreview.SendOneTimePassword("", false); // Send the user harsh code
        }
        else // Not logged in
        {
            var tmpMsisdn = currentPreview.currentMsisdnText.value; // Get the MSISDN that the user entered
            if(tmpMsisdn != "") // If the user entered MSISDN
            {
                if(IsMsisdnValid(tmpMsisdn)) // Check MSISDN validity
                    currentPreview.SendOneTimePassword(tmpMsisdn, false); // Send the user harsh code
            }
            else // The user didn't enter msisdn, then let him.
            {
                // If posible, reset previews Graphics CurrentPreviewObj object
                if(previousPreview != null)
                    previousPreview.ResetGrafics();
                currentPreview.ClearText(); // Clear the MSISDN text box
                currentPreview.ShowStepTwo(); // Show step 2
            }
        }
    }
}

//////////////////////////////////////////////////////
/// Reset the current preview CurrentPreviewObj object
//////////////////////////////////////////////////////
function ResetCurrentPreview()
{
    if(goBackToStepFour) // If need to reset back to step 4
    {
        goBackToStepFour = false;
        currentPreview.ShowStepFour();
    }
    else // Reset to step 1
    {
        currentPreview.ShowStepOne();
    }
}

//////////////////////////////////////////////////
/// Go to step 4, the harsh code confirmation step
//////////////////////////////////////////////////
function CurrentPreviewConfirmHarshCodeStep()
{
    currentPreview.ShowStepFour();
}

/////////////////////////////
/// Go to send to friend page
/////////////////////////////
function SendToFriend(cpid, apid, LanguageId)
{
	location.href = 'SendToFriend5.aspx?cpID=' + cpid + '&apID=' + apid + '&LanguageId=' + LanguageId;
}

//////////////////////////////////
/// Go to games general lobby page
//////////////////////////////////
function GetGameInfo(nodeid, cpid, apid, LanguageId)
{
    var url = "";
    
    if(nodeid == "") // Get by cp ap
        url = 'games_general_lobby.aspx?cpID=' + cpid + '&apID=' + apid + '&LanguageId=' + LanguageId;
    else // Get by nodeid
        url = 'games_general_lobby.aspx?NodeId=' + nodeid + '&LanguageId=' + LanguageId;

	 location.href = url;
}

///////////////////////////////////////////
/// Set the isHarshLoggedIn global veriable
///////////////////////////////////////////
function SetIsHarshLoggedIn(harshLoggedIn)
{
    if(isHarshLoggedIn == false)
        isHarshLoggedIn = harshLoggedIn;
}

/////////////////////////////
/// Check for digits only 0-9
/////////////////////////////
function CheckNumber(KeyEntered)
{
    return (KeyEntered > 47 && KeyEntered  < 58) ? true : false;
}

/************************
 * Private global methods
 ************************/
 


/////////////////////////////////////////////////////
/// HttpRequest to get file path form mpower by cp ap
/////////////////////////////////////////////////////
function GetFromMPower(cpid, apid, LanguageId)
{	
	xmlhttp=null
    
    // code for Mozilla, etc.
    if ((window.XMLHttpRequest)&& (navigator.appName != "Microsoft Internet Explorer"))     { xmlhttp=new XMLHttpRequest()  }
    
    // code for IE
    else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }

    if (xmlhttp!=null)
    {
      // xmlhttp.onreadystatechange=state_Change
         xmlhttp.open("GET", 'GetFlavorSelection.aspx?cpid='+ cpid +'&apid='+apid + '&LangID=' + LanguageId, false);    
         xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         xmlhttp.send(null); 
      	 return xmlhttp.ResponseText;
    }
    
    else { alert("Your browser does not support XMLHTTP.")  } 
}

///////////////////////////////////
/// Creates a player for audio file
///////////////////////////////////
function GetAudioPlayer(path)
{
    var playerHtml = '<OBJECT ID="PlayerObj"'
				   + 'CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"'
				   + 'height="0" width="0">'
				   + '<PARAM name="URL" value="'+ path + '">'
				   + '<PARAM name="autoStart" value="True">'
				   + '</OBJECT>';
				   
    return playerHtml;
}

///////////////////////////////////
/// Creates a player for video file
///////////////////////////////////
function GetVideoPlayer(path)
{
	var playerHtml = '<OBJECT id=mediaPlayer classid=CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95 ' +
                  '  width=128 height=128 type=application/x-oleobject > ' +
                  ' <PARAM NAME="AudioStream" VALUE="1"> ' +
                  ' <PARAM NAME="AutoSize" VALUE="0"> ' +
                  ' <PARAM NAME="AutoStart" VALUE="-1"> ' +
                  ' <PARAM NAME="AnimationAtStart" VALUE="-1"> ' +
                  ' <PARAM NAME="AllowScan" VALUE="-1"> ' +
                  ' <PARAM NAME="AllowChangeDisplaySize" VALUE="1"> ' +
                  ' <PARAM NAME="BufferingTime" VALUE="5"> ' +
                  ' <PARAM NAME="ClickToPlay" VALUE="-1"> ' +
                  ' <PARAM NAME="CursorType" VALUE="0"> ' +
                  ' <PARAM NAME="CurrentPosition" VALUE="-1"> ' +
                  ' <PARAM NAME="DisplayBackColor" VALUE="0"> ' +
                  ' <PARAM NAME="DisplayForeColor" VALUE="16777215"> ' +
                  ' <PARAM NAME="DisplayMode" VALUE="0"> ' +
                  ' <PARAM NAME="DisplaySize" VALUE="0"> ' +
                  ' <PARAM NAME="Enabled" VALUE="1"> ' +
                  ' <PARAM NAME="EnableFullScreenControls" VALUE="0"> ' +
                  ' <PARAM NAME="EnableTracker" VALUE="-1"> ' +
                  ' <PARAM NAME="Filename" VALUE="' + path + '"> ' +
                  ' <PARAM NAME="PlayCount" VALUE="100"> ' +
                  ' <PARAM NAME="SendErrorEvents" VALUE="True"> ' +
                  ' <PARAM NAME="SendKeyboardEvents" VALUE="0"> ' +
                  ' <PARAM NAME="ShowCaptioning" VALUE="0"> ' +
                  ' <PARAM NAME="ShowControls" VALUE="0"> ' +
                  ' <PARAM NAME="ShowAudioControls" VALUE="0"> ' +
                  ' <PARAM NAME="ShowDisplay" VALUE="0"> ' +
                  ' <PARAM NAME="ShowGotoBar" VALUE="0"> ' +
                  ' <PARAM NAME="ShowPositionControls" VALUE="0"> ' +
                  ' <PARAM NAME="ShowStatusBar" VALUE="0"> ' +
                  ' <PARAM NAME="ShowTracker" VALUE="0">       ' +
                  ' <PARAM NAME="WindowlessVideo" VALUE="-1">    ' +
                  '</OBJECT>';
	
	return playerHtml;
}
 
////////////////////////////////////////////////////////////////////////
/// HttpRequest to download an item to user's mobile by cp ap and msisdn
////////////////////////////////////////////////////////////////////////
function ServerRequest(cp, ap, msisdn, LanguageId)
{
	var url;
	if(msisdn==null)
	{
		url = 'ItemDownloadsLoggedIN.aspx?cpID=' + cp + '&apID=' + ap + '&LanguageId=' + LanguageId;
	}
	else
	{
		url = 'ItemDownloads.aspx?cpID=' + cp + '&apID=' + ap + '&msisdn=' + msisdn + '&LanguageId=' + LanguageId;
	}
		
	xmlhttp=null
    
    // code for Mozilla, etc.
    if (window.XMLHttpRequest)     { xmlhttp=new XMLHttpRequest()  }
    
    // code for IE
    else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }

    if (xmlhttp!=null)
    {
         xmlhttp.open("GET", url, false);
	     xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         xmlhttp.send(null); 
      	 var result = xmlhttp.responseText;	
	     return ExtractMessageFromXML(result);
    }
    else { alert("Your browser does not support XMLHTTP.")  } 
}

///////////////////////////////////////////////////////////////////
/// HttpRequest to send a user a harsh code to his mobile by msisdn
///////////////////////////////////////////////////////////////////
function ServerRequestSendHarshCode(msisdn)
{
	var url;
	
	if(msisdn=="")
	{
		url = "ItemDownloadsSendOneTimePassword.aspx";
	}
	else
	{
		url = "ItemDownloadsSendOneTimePassword.aspx?msisdn=" + msisdn;
	}
		
	xmlhttp=null
    
    // code for Mozilla, etc.
    if (window.XMLHttpRequest)     { xmlhttp=new XMLHttpRequest()  }
    
    // code for IE
    else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }

    if (xmlhttp!=null)
    {
	    xmlhttp.open("GET", url, false);
	    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    xmlhttp.send(null); 
	    var result = xmlhttp.responseText;
	    return ExtractMessageFromXML(result);
    }	
    else { alert("Your browser does not support XMLHTTP.")  } 	
}



/////////////////////////////////////////////////////////////////////////////////////////////////////
/// HttpRequest to CheckMsisdnBalance
/////////////////////////////////////////////////////////////////////////////////////////////////////
function CheckMsisdnBalance(msisdn)
{
	var url = "CheckMsisdnBalance.aspx?msisdn=" + msisdn;
		
	xmlhttp=null
    
    // code for Mozilla, etc.
    if (window.XMLHttpRequest)     { xmlhttp=new XMLHttpRequest()  }
    
    // code for IE
    else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }

    if (xmlhttp!=null)
    {
    	var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	    xmlhttp.open("GET", url, false);
	    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    xmlhttp.send(null); 
	    var result = xmlhttp.responseText;
	    return ExtractMessageFromXML(result);
    }	
}



/////////////////////////////////////////////////////////////////////////////////////////////////////
/// HttpRequest to confirm an entered harsh code by a user, against the harsh code sent to his mobile
/////////////////////////////////////////////////////////////////////////////////////////////////////
function ServerRequestConfirmHarshCode(harshCode)
{
	var url = "ItemDownloadsSendOneTimePassword.aspx?HarshCode=" + harshCode;
		
	xmlhttp=null
    
    // code for Mozilla, etc.
    if (window.XMLHttpRequest)     { xmlhttp=new XMLHttpRequest()  }
    
    // code for IE
    else if (window.ActiveXObject) { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP") }

    if (xmlhttp!=null)
    {
    	var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	    xmlhttp.open("GET", url, false);
	    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	    xmlhttp.send(null); 
	    var result = xmlhttp.responseText;
	    return ExtractMessageFromXML(result);
    }	
}

////////////////////////////////////////////////
/// Get the returned message from an HttpRequest
////////////////////////////////////////////////
function ExtractMessageFromXML(xmlString)
{

	 var result;	
	 	
	// code for IE
    if (window.ActiveXObject)
    {
         xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
         xmlDoc.async=false;
         xmlDoc.loadXML(xmlString);  
	   
	     try        {  result= xmlDoc.getElementsByTagName('message').item(0).text  }   
	     catch(e)   {  result = xmlString; }  	
	     if(result == "over 3 times")
            location.href = "Login.aspx";
	     return result;    
     }
       

    // code for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
    {      
        xmlDoc=document.implementation.createDocument("","",null);  
  
       var oParser = new DOMParser();
       var oXmlDom = oParser.parseFromString( xmlString , "text/xml");
       var oRoot = oXmlDom.documentElement;
       
       try        { result  =  oRoot.getElementsByTagName('message').item(0).text; }   
	   catch(e)   {  result =  xmlString;                }  	
	    
	    return result;       
     }
     
     else  {  alert('Your browser cannot handle this script');  }
    
}


/////////////////////////////////////////////
/// Finds out if user entered MSISDN is valid
/////////////////////////////////////////////
function IsMsisdnValid(msisdn)
{
    // The regular expresion
	pattern = new RegExp("[0][5]\\d{8}");
	
	if(pattern.test(msisdn)) // If MSISDN valid
	{
	 
        SetCookie('msisdn',msisdn);
		return true;
	}
	else // If MSISDN not valid
	{
	    SetCookie('msisdn','');
	    currentPreview.currentMessageLable.innerText = "מספר שגוי"; // Set message
        currentPreview.ShowStepThree(); // Show message (step 3)
	    return false;
	}
}


		function SetCookie(cookieName,cookieValue) 
		{
			//var today = new Date();
			//var expire = new Date();
			//if (nDays==null || nDays==0) nDays=1;
			//expire.setTime(today.getTime() + 3600000*24*nDays);
			document.cookie = cookieName+"="+escape(cookieValue)
						//+ ";expires="+expire.toGMTString();
		}

		function ReadCookie(cookieName) 
		{
			var theCookie=""+document.cookie;
			var ind=theCookie.indexOf(cookieName);
			if (ind==-1 || cookieName=="") return ""; 
			var ind1=theCookie.indexOf(';',ind);
			if (ind1==-1) ind1=theCookie.length; 
			return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
		}
