function PreviewPopup(popupId, itemId) {
    // popUp Element's Id
    this.popupId                    = popupId;

    // popup reference to self
    this.popupName                  = '';

    // id for current copy of original popup
    this.curPopupId                 = '';

    // item to popup
    this.itemId                     = itemId;
    this.open                       = 0;

    this.data                       = new Array();

    // offsets for new popup
    this.offsetLeft                 = 0;
    this.offsetTop                  = 0;

    this.origPopupOffsetLeft        = 0;
    this.origPopupOffsetTop         = 0;

    this.setOffset                  = setOffset;

    this.previewPopup               = previewPopup;
    this.movePopup                  = movePopup;
    this.closePopup                 = closePopup;
    this.transitionType             = '';
    this.setPopupName               = setPopupName;
    this.setPopupType               = setPopupType;
    this.setData                    = setData;
    this.getData                    = getData;
    this.setFlashPreviewDimensions  = setFlashPreviewDimensions;
    
    var sector;

    var me                          = this;
    
    function getData(field) {
        return this.data[field];
    }

    function setData(field, value) {
        this.data[field] = value;
    }

    function setOffset(l, t) {
        this.offsetLeft = l;
        this.offsetTop  = t;
    }

    function setPopupName(n) {
        this.popupName = n;
    }

    function setPopupType(t) {
        this.customFunction = eval(t);
    }

    function setFlashPreviewDimensions(h,w) {
        this.setData('preview_height', h);
        this.setData('preview_width', w);
    }

    function previewPopup() {
        popupDiv = document.getElementById(this.popupId);

        itemDiv = document.getElementById(this.itemId);
        parentItem = itemDiv.parentNode;

        popup_copy = popupDiv.cloneNode(true);
        popup_copy.id = this.itemId + '_' + this.popupId;
        this.curPopupId = popup_copy.id;

        oldPattern = this.popupId;
        newPattern = this.curPopupId;
        this.modIds(popup_copy, oldPattern, newPattern);

        parentItem.appendChild(popup_copy);

        var offsetL = 0;
        var offsetT = 0;

        me.movePopup();

        // changed the popup style
        $(this.curPopupId).setStyle({
            position:   'absolute',
            display:    '',
            opacity:    1,
            filter:     'alpha(opacity:100)'
        });

        if (this.customFunction) {
            this.customFunction();
        }

        //new Effect.Opacity(this.curPopupId, {duration:0.35, from:0.0, to:0.9999999} );
        me.open = 1;
    }

    function movePopup() {
        var offsetL = 0;
        var offsetT = 0;

        var obj = $(this.itemId);

        do {
            offsetT += obj.offsetTop  || 0;
            offsetL += obj.offsetLeft || 0;
            obj = obj.offsetParent;
        } while (obj && obj.tagName != 'BODY');

        // offset the left and top of the original item for the popup
        offsetL = offsetL - this.offsetLeft;
        offsetT = offsetT - this.offsetTop;
        
        $(this.curPopupId).style.left = offsetL + 'px';
        $(this.curPopupId).style.top = offsetT + 'px';
    }

    this.modIds = function(node, oldPattern, newPattern) {
        var child, nodes = node.childNodes;
        for (var i=0, len=nodes.length; i<len; i++){
            child = nodes[i];
            if ('string' == typeof child.id){
                child.id = child.id.replace(oldPattern, newPattern);
            }
            if (child.childNodes && child.childNodes.length){
                this.modIds(child, oldPattern, newPattern);
            }
        }
    }

    function Popup() {
        /** Music section **/
        if ($(this.itemId+'_legend_icons')) {
            //var download_icons = $(this.itemId+'_legend_icons').getElementsByClassName('legend');
            //getElementsByClassName seems to have IE issue with prototype.js $$ should be used to make it work
            var download_icons = $$('.legend');
            
            for(i=0;i<download_icons.length;i++) {
                var icon_id = download_icons[i].id;
                var sector = icon_id.replace(this.itemId+'_pub_','');

                // Set credit check link(s) for music sectors
                if ($(this.itemId+'_pub_'+sector)) { 
                    $(this.curPopupId+'_pub_'+sector).style.display = 'block';
                    //$(this.curPopupId+'_pub_'+sector).setAttribute('onClick', "creditCheck('"+this.getData('msisdn')+"', "+$(this.itemId+'_sector_id').innerHTML + ", " + $(this.itemId+'_credit_cost').innerHTML + ");");
                    $(this.curPopupId+'_pub_'+sector).setAttribute('onClick', "creditCheck('"+this.getData('msisdn') + "', " + sector + ", " + $(this.itemId+'_credit_cost').innerHTML + ", " + $(this.itemId+'_publication_id_' + sector).innerHTML + ");");
                    $(this.curPopupId+'_pub_'+sector).parentNode.innerHTML = $(this.curPopupId+'_pub_'+sector).parentNode.innerHTML;
                } else if ($(this.curPopupId+'_pub_'+sector)) {
                    $(this.curPopupId+'_pub_'+sector).style.display = 'none';
                }
            }
        }

        // Change the song name and link
        if ($(this.itemId+'_song_name')) {
            $(this.curPopupId+'_song_name').innerHTML = $(this.itemId+'_song_name').innerHTML;
            $(this.curPopupId+'_song_name').href = $(this.itemId+'_url').innerHTML;
        }

        // Change the artist name and link
        if ($(this.itemId+'_artist_name')) {
            $(this.curPopupId+'_artist_name').innerHTML = $(this.itemId+'_artist_name').innerHTML;
            $(this.curPopupId+'_artist_name').href = $(this.itemId+'_artist_url').innerHTML;
        }

        // Change the album art
        if ($(this.itemId+'_album_art')) {
            $(this.curPopupId+'_album_art').src = $(this.itemId+'_album_art').src;
        }
        
        // change flash preview
        if ($(this.curPopupId + '_preview')) {
            var ringtoneSwf = '/template/skin/' + this.getData('skinId') + '/swf/play_v3.swf?id=' + $(this.itemId + '_publication_id').innerHTML + '-2100-ringtone-' + $(this.itemId + '_sector_id').innerHTML;
            var so = new SWFObject(ringtoneSwf, this.curPopupId + '_preview_swf',this.getData('preview_height'),this.getData('preview_width'),'7');
            so.addVariable("allowScriptAccess", 'sameDomain');
            so.addVariable("movie", ringtoneSwf);
            so.addVariable("quality", "high");
            so.addVariable("scale", "exactfit");
            so.addVariable("wmode", "transparent");
            so.addVariable("bgcolor", "transparent");
            so.write(this.curPopupId + '_preview');
        }


        /** Non-music section **/
        
        // Set credit check link for non-music
        if ($(this.curPopupId+'_link')) {
            $(this.curPopupId+'_link').setAttribute('onClick', "creditCheck('"+this.getData('msisdn')+"', "+$(this.itemId+'_sector_id').innerHTML + ", " + $(this.itemId+'_credits_cost').innerHTML + ");");
            $(this.curPopupId+'_link').parentNode.innerHTML = $(this.curPopupId+'_link').parentNode.innerHTML;
        }

        // Change non-music image
        if ($(this.itemId+'_image')) {
            $(this.curPopupId+'_image').src = $(this.itemId+'_image').src;
        }


        /** Combined music and non-music section **/
        
        // Change the "share" onClick
        if ($(this.curPopupId + '_share')) {
            $(this.curPopupId + '_share').setAttribute('onClick',"showTafSw('" + $(this.itemId + '_page_type').innerHTML + "', " + $(this.itemId + '_publication_id').innerHTML + ", null)");
            $(this.curPopupId + '_share').parentNode.innerHTML = $(this.curPopupId + '_share').parentNode.innerHTML;
        }
    }

    function PurchasePopup() {
        
        var publicationId = this.getData('publicationId');
        var sectorId      = this.getData('sectorId');
        var deviceId      = this.getData('deviceId') ? this.getData('deviceId') : "''";


        /** Music section **/
       
        // Change the "share" onClick
        if ($(this.curPopupId + '_share')) {
            $(this.curPopupId + '_share').setAttribute('onClick',"showTafSw('" + $(this.itemId + '_page_type').innerHTML + "', " + $(this.itemId + '_publication_id').innerHTML + ", null)");
            $(this.curPopupId + '_share').parentNode.innerHTML = $(this.curPopupId + '_share').parentNode.innerHTML;
        }
        
        // Change the song name and link
        if ($(this.itemId+'_song_name')) {
            $(this.curPopupId+'_song_name').innerHTML = $(this.itemId+'_song_name').innerHTML;
            //$(this.curPopupId+'_song_name').href = $(this.itemId+'_url').innerHTML;
            $(this.curPopupId+'_song_name').href = $(this.itemId+'_url_'+sectorId).innerHTML;
        }

        // Change the artist name and link
        if ($(this.itemId+'_artist_name')) {
            $(this.curPopupId+'_artist_name').innerHTML = $(this.itemId+'_artist_name').innerHTML;
            $(this.curPopupId+'_artist_name').href = $(this.itemId+'_artist_url').innerHTML;
        }

        // Change the album art
        if ($(this.itemId+'_album_art')) {
            $(this.curPopupId+'_album_art').src = $(this.itemId+'_album_art').src;
        }

        // Change the album art
        if ($(this.curPopupId+'_more_by')) {
            $(this.curPopupId+'_more_by').innerHTML = $(this.curPopupId+'_more_by').innerHTML + " " + $(this.itemId+'_artist_name').innerHTML;
            $(this.curPopupId+'_more_by').href = $(this.itemId+'_artist_url').innerHTML;
        }
        
        // If it has been downloaded...
        if ($(this.itemId+'_downloaded')) {
            if ($(this.itemId+'_downloaded').innerHTML == true) { 
                // Change the downloaded date
                if ($(this.itemId+'_last_downloaded')) {
                    $(this.curPopupId+'_last_downloaded').innerHTML = $(this.itemId+'_last_downloaded').innerHTML;
                }
                
                // Change the resend button
                if ($(this.itemId+'_order_token') && $(this.curPopupId+'_ringtone_link')) {
                //    $(this.curPopupId+'_order_token').innerHTML = $(this.itemId+'_order_token').innerHTML;
                    $(this.curPopupId+'_ringtone_link').setAttribute('onclick',"resendItem('" + $(this.itemId+'_order_token').innerHTML + "', '" + this.curPopupId + "');");
                }
            } 
        }
        
        /** Non-music section **/

        if ($(this.itemId+'_image')) {
            $(this.curPopupId+'_image').src = $(this.itemId+'_image').src;
        }


        /** Combined music and non-music section **/

        if ($(this.curPopupId+'_link')) { 
            if (publicationId && sectorId) {
                $(this.curPopupId+'_link').setAttribute('onclick',"send_object(" + publicationId + ", " + sectorId + ", " + this.getData('msisdn') + ", '', " + deviceId +");");
            } else {
                $(this.curPopupId+'_link').setAttribute('onclick',"send_object(" + $(this.itemId + '_publication_id').innerHTML + ", " + $(this.itemId + '_sector_id').innerHTML + ", " + this.getData('msisdn') + ", '', " + deviceId +");");
            }
            $(this.curPopupId + '_link').parentNode.innerHTML = $(this.curPopupId + '_link').parentNode.innerHTML;
        }
        
        if (this.getData('credits_left') > 2000) {
            if ($(this.curPopupId+'_credits_remain')) {
                $(this.curPopupId+'_credits_remain').style.display = 'none';
            }
            if ($(this.curPopupId+'_credit_price')) {
                $(this.curPopupId+'_credit_price').style.display = 'none';
            }
            if ($(this.curPopupId+'_unlimited_credits_left')) {
                $(this.curPopupId+'_unlimited_credits_left').style.display = '';
            }
        } else {
            if ($(this.curPopupId+'_credits_left')) {
                $(this.curPopupId+'_credits_left').innerHTML = this.getData('credits_left');
            }
        }

        if ($(this.curPopupId+'_credit_cost')) {
            $(this.curPopupId+'_credit_cost').innerHTML = $(this.itemId+'_credit_cost').innerHTML;
        }

        if ($(this.curPopupId+'_price')) {
            $(this.curPopupId+'_price').innerHTML = $(this.itemId+'_currency').innerHTML + $(this.itemId+'_price').innerHTML;
        }

        if (sectorId) {
            $(this.curPopupId+'_sector_id').innerHTML = sectorId;
        } else if ($(this.curPopupId+'_sector_id')) {
            $(this.curPopupId+'_sector_id').innerHTML = $(this.itemId + '_sector_id').innerHTML;
        }

        if (publicationId) {
            $(this.curPopupId+'_publication_id').innerHTML = publicationId;
        } else if ($(this.curPopupId+'_publication_id')) {
            $(this.curPopupId+'_publication_id').innerHTML = $(this.itemId + '_publication_id').innerHTML;
        }
    }

    function PurchasePopupConfirm() {

        var sectorId      = this.getData('sectorId');
        
        // Change the "share" onClick
        if ($(this.curPopupId + '_share')) {
            $(this.curPopupId + '_share').setAttribute('onClick',"showTafSw('" + $(this.itemId + '_page_type').innerHTML + "', " + $(this.itemId + '_publication_id').innerHTML + ", null)");
            $(this.curPopupId + '_share').parentNode.innerHTML = $(this.curPopupId + '_share').parentNode.innerHTML;
        }
        
        if (this.getData('credits_left') > 2000) {
            if ($(this.curPopupId+'_credits_remain')) {
                $(this.curPopupId+'_credits_remain').style.display = 'none';
            }
            if ($(this.curPopupId+'_unlimited_credits_left')) {
                $(this.curPopupId+'_unlimited_credits_left').style.display = '';
            }
        } else {
            if ($(this.curPopupId+'_credits_left')) {
                $(this.curPopupId+'_credits_left').innerHTML = this.getData('credits_left');
            }
        }

        /** Music section **/

        // Change the song name and link
        if ($(this.itemId+'_song_name')) {
            $(this.curPopupId+'_song_name').innerHTML = $(this.itemId+'_song_name').innerHTML;
            //$(this.curPopupId+'_song_name').href = $(this.itemId+'_url').innerHTML;
            $(this.curPopupId+'_song_name').href = $(this.itemId+'_url_'+sectorId).innerHTML;
        }

        // Change the artist name and link
        if ($(this.itemId+'_artist_name')) {
            $(this.curPopupId+'_artist_name').innerHTML = $(this.itemId+'_artist_name').innerHTML;
            $(this.curPopupId+'_artist_name').href = $(this.itemId+'_artist_url').innerHTML;
        }

        // Change the album art
        if ($(this.itemId+'_album_art')) {
            $(this.curPopupId+'_album_art').src = $(this.itemId+'_album_art').src;
        }

        // Change the more by link
        if ($(this.curPopupId+'_more_by')) {
            $(this.curPopupId+'_more_by').innerHTML = $(this.itemId+'_artist_name').innerHTML;
            $(this.curPopupId+'_more_by').href = $(this.itemId+'_artist_url').innerHTML;
        }

        if ($(this.curPopupId+'_ringtone_link')) {
            $(this.curPopupId+'_ringtone_link').setAttribute('onclick',"resendItem('" + this.getData('orderToken') + "', '" + this.curPopupId + "');");
            $(this.curPopupId + '_ringtone_link').parentNode.innerHTML = $(this.curPopupId + '_ringtone_link').parentNode.innerHTML;
        }

        if ($(this.curPopupId+'_link')) {
            $(this.curPopupId+'_link').setAttribute('onclick',"resendItem('" + this.getData('orderToken') + "', '" + this.curPopupId + "');");
            $(this.curPopupId + '_link').parentNode.innerHTML = $(this.curPopupId + '_link').parentNode.innerHTML;
        }


        /** Non-music section **/

        if ($(this.itemId+'_image')) {
            $(this.curPopupId+'_image').src = $(this.itemId+'_image').src;
        }
    }

    function closePopup() {
        if (typeof(ClickTaleExec) == 'function') {
            // if this doesnt work, create a new instance of the class and close it.
            ClickTaleExec("closePopups()"); // if clicktale exists
        }
        
        if (me.curPopupId!='') {
            me.hidePopup();
        	//new Effect.Opacity(this.curPopupId, {duration:0.35, from:0.9999999, to:0.0, afterFinish: me.hidePopup} );
        }
    }

    this.hidePopup = function() {
        curPopup = document.getElementById(me.curPopupId);
        if (curPopup) {
            curPopup.parentNode.removeChild(curPopup);
            me.curPopupId = '';
            me.open = 0;
            return false;
        }
    }
}

// Global vars and functions
var activeItem = '';
var PopupVert = null;
var PopupHor = null;
var PurchasePopup = null;
var PurchaseConfirmPopup = null;
var curPopup = null;

function closePopups() {
    // hide Popups
    if (PopupHor != undefined && PopupHor.open) {
        closePopupHor();
    }
    if (PopupVert != undefined && PopupVert.open) {
        closePopupVert();
    }
    if (PurchasePopup != undefined && PurchasePopup.open) {
        closePurchasePopup();
    }
    if (PurchaseConfirmPopup != undefined && PurchaseConfirmPopup.open) {
        closePurchaseConfirmPopup();
    }
    
    activeItem = '';
}

function closePopupVert() {
    PopupVert.closePopup();
}

function closePopupHor() {
    PopupHor.closePopup();
}

function closePurchasePopup() {
    PurchasePopup.closePopup();
}

function closePurchaseConfirmPopup() {
    PurchaseConfirmPopup.closePopup();
}

function creditCheck(msisdn, sector_id, credit_cost, publication_id) {
    // create ajax call with form values
    var url = '/script/ajax/product-purchase/get-credits.php';
    var params = 'msisdn='+msisdn+'&sector_id='+sector_id+'&credit_cost='+credit_cost+'&publication_id='+publication_id;
    var mfRequest = new Ajax.Request(url, {method:'post', parameters:params, onComplete:postCreditCheck});
}

function postCreditCheck(mfRequest) {
    var res = mfRequest.responseText;
    
    credit_array = eval('(' + res + ')');
    
    //phone-check redirection is done here
    if(credit_array['device-check']=="yes"){
    	var dummy_url;
    	if ($(activeItem.id + '_url_' + credit_array['sector_id'])) {
            dummy_url = $(activeItem.id + '_url_' + credit_array['sector_id']).innerHTML;
        } else {
            dummy_url = $(activeItem.id + '_url').innerHTML;
        }        
    	window.location = '/phone-check?phoneCheckDestination='+dummy_url;
    	return false;
    }
    
    if (credit_array['credits_remaining'] == null || credit_array['credit_cost'] > credit_array['credits_remaining']) {
        //document.location.href = $(activeItem.id + '_url').innerHTML;
        // if they don't have enough credits, redirect to purchase page.
        if ($(activeItem.id + '_url_' + credit_array['sector_id'])) {
            document.location.href = $(activeItem.id + '_url_' + credit_array['sector_id']).innerHTML;
        } else {
            document.location.href = $(activeItem.id + '_url').innerHTML;
        }
    } else {
        createPurchasePopup(credit_array, activeItem);
    }
}

function createPurchasePopup(credit, item) {
    eval("createPurchasePopup_" + credit['type'] + "(credit, item);");
}

function send_object(publicationId, sectorId, msisdn, type, deviceId) {
    // create ajax call with form values
    var url = '/script/ajax/send-object/send-object.php';
    var params = 'publicationId='+publicationId+'&sectorId='+sectorId+'&msisdn='+msisdn+'&deviceId='+deviceId;
    var mfRequest = new Ajax.Request(url, {method:'post', parameters:params, onComplete:postSendObject});
}

function postSendObject(mfRequest) {
    var res = mfRequest.responseText;
    
    response = eval('(' + res + ')');
    
    orderToken = response['orderToken'];
    sectorId = response['sectorId'];

    createPurchaseConfirmPopup(orderToken, activeItem, PurchasePopup.getData('contentType'), PurchasePopup.getData('credits_left'), sectorId);
}

function createPurchaseConfirmPopup(orderToken, item, type, credits_left, sector_id) {
    eval("createPurchaseConfirmPopup_" + type + "(orderToken, item, credits_left, sector_id);");
}

function resendItem(orderToken, id) {
    var url = '/script/ajax/my-flycell/resend.php';
    var pars = 'orderToken='+orderToken;
    var myAjax = new Ajax.Request(
    url, 
    {
        method: 'get', 
        parameters: pars, 
        onComplete: function () { 
            if ($(id + '_sent_text')) {
                $(id + '_sent_text').style.display = 'none';
                $(id + '_sent_text').parentNode.innerHTML = $(id + '_sent_text').parentNode.innerHTML
            }
            $(id + '_resent_text').style.display = '';
            $(id + '_resent_text').parentNode.innerHTML = $(id + '_resent_text').parentNode.innerHTML
        }
    });
}

