// Global Variables
/*For MyMovies Download UI
var varMovieContent = '';*/
/*For Search string
var varSearchString = '';*/

/* Download Movie URL - Not working on chrome<a. tag 'href' after 'click'*/
          var varMovieURL ='';

//AceTrax global functions used for contact us. Commeted here because calling the AceTrax directly
/*
// Global Variables
userIsAuthenticated = false;

$(document).ready(function () {

    //CLEAR CACHE FROM AJAX
    $.ajaxSetup({ cache: false })

    userIsAuthenticated = ($(".login_div .username span").css("display") != "none");

    // ******************************* MENU SELECT ****************************** //

    var page_id = $("#page_id").text();

    switch (page_id) {
                    
       case "4d7c7db4-f148-4310-bdce-f1226a1ef143": //Contact Us
            //$("#page_id").text("Contact Us");
			addContactCustomerCareFormValidator();
            break;

    }
    // ******************************* MENU SELECT ****************************** //
});


// *******************************  Contact Us  ******************************* //

function ajaxPostToContactCustomerCare() { alert("vou mandar mail11");

    //$("#contactUsSubmitBtn").parent().html('<img src="acetrax/system/img/ajax-loader.gif" />');
    $("#contactUsSubmitBtn").parent().hide();
    $("#loaderIcon").show();
    
    $.ajax({
        type: "POST",
        url: "ContactCustomerCare.aspx",
        data: { emailadress: $("#emailadress").val(), username: $("#username").val(),
            movietitle: $("#movietitle").val(), opsystem: $("#opsystem").val(),
            browser: $("#browser").val(), description: $("#description").val()
        },
        async: true,

        success: function (data, textStatus, XMLHttpRequest) { alert("vou mandar mail12");
            if (data != "" && data != undefined) {
                //alert(data);

                var result = eval('(' + data + ')');
                var errorCode = result.response.errorCode;

                var userName = escape($('#username').val());
                var emailAdress = escape($('#emailadress').val());
                var movieTitle = escape($('#movietitle').val());
                var os = escape($('#opsystem').val());
                var browser = escape($('#browser').val());
                var description = escape($('#description').val());

                $("#contactUsForm").hide();

                if (errorCode != '0') { alert("vou mandar mail13");
                    //alert("vou mandar mail");
                    document.location = 'mailto:cc_support@acetrax.com?subject=Contact%20from%30User%20' + userName + '&body=mail body' + emailAdress + '%0A%0aMovie Title: ' + movieTitle + '%0A%0aOperation System: ' + os + '%0A%0aBrowser: ' + browser + '%0A%0aDescription:%0A%0a' + description + '%0A%0a';

                    $("#contactUsErrorDiv").show();
                }
                else { alert("vou mandar mail14");
                    $("#contactUsOkDiv").show();
                }


            } else { alert("vou mandar mail15");
                document.location = 'mailto:cc_support@acetrax.com?subject=Contact from User ' + $('#username').val() + '&amp;body=Email Address: ' + $('#emailadress').val() + '%0A%0aMovie Title: ' + $('#movietitle').val() + '%0A%0aOperation System: ' + $('#opsystem').val() + '%0A%0aBrowser: ' + $('#browser').val() + '%0A%0aDescription:%0A%0a' + $('#description').val() + '%0A%0a';
                $("#contactUsErrorDiv").show();
            }
        },

        error: function () { alert("vou mandar mail16");
            $("#contactUsForm").hide();
            $("#contactUsErrorDiv").show();
            document.location = 'mailto:cc_support@acetrax.com?subject=Contact from User ' + $('#username').val() + '&amp;body=Email Address: ' + $('#emailadress').val() + '%0A%0aMovie Title: ' + $('#movietitle').val() + '%0A%0aOperation System: ' + $('#opsystem').val() + '%0A%0aBrowser: ' + $('#browser').val() + '%0A%0aDescription:%0A%0a' + $('#description').val() + '%0A%0a';
        }

    });
}

function addContactCustomerCareFormValidator() {

    $("#contactUs").validate({
        rules: {
            emailadress: { required: true, email: true },
            username: { required: true },
            description: { required: true }
        },
        messages: {
            emailadress: {
                required: $("#missingEmail").html(),
                email: $("#invalidEmail").html()
            },
            username: {
                required: $("#missingUser").html()
            },
            description: {
                required: $("#missingDesc").html()
            }
        },
        submitHandler: function () {
            ajaxPostToContactCustomerCare();
        }

    });

}



// *******************************  Contact Us  ******************************* //*/


/* //////////////////////////         SignIn script method  ////////////////////    */

/*GET PARENT TYPE*/
/*GET PARENT WINDOW TYPE : Fix for issue that on popup close or (X) click page is redirecting to homepage i.e. Issue #AT-1433*/
function setPageType(popupUrl) 
{
	//Get parent page URL to set Cookie
	var varParentURL = document.location.href;
	var varParentRelativeURL = document.location.pathname;
	var varParentParams = "";
	var arrParentParams=new Array();

	//Check if params exists or not
	if (document.location.search != "")
	{
		varParentParams = document.location.search;
		varParentParams = varParentParams.substring(1);
		arrParentParams = varParentParams.split("&");
	}	
	 
	var IndexOfEqual=0;
	var Pagetemp = '';
	var keyName = '';
	var keyValue = '';
	var varSearchVal = '';	

	//Add page name to URL
	/*if(document.location.pathname=='/')
	{
		//HOMEPAGE
		pageType = "Generic.aspx?type=homepage";
	}
	else
	{*/
	//Other pages
	if (varParentRelativeURL == '/' && (document.location.search == "" || varParentParams == 'refreshcache=1')) {
	    varParentRelativeURL = "/Home.aspx";
	}
		pageType = varParentRelativeURL.replace('/', '');//Remove slash
		
		// Special case - For search page
		if (varParentRelativeURL.indexOf("Search.aspx")>-1)
		{
			// 'hdnSearchString' store searched input string as page not maintaining that string in first and unmatched case
			if (document.getElementById('hdnSearchString'))
			{
				varSearchVal = document.getElementById('hdnSearchString').value; 
			}		
		}
		
		if (arrParentParams.length > 0) 
		{
			/*Added case - For development purpose as when 'refreshcache=1' is included in URL*/
			if(arrParentParams.length == 1 && arrParentParams[0] == "refreshcache=1");
			/*Added case - To ignore 'showpopupcode' as only param in URL*/
			else if(arrParentParams.length == 1 && arrParentParams[0].toString().toLowerCase().indexOf("showpopupcode") > -1);
			else
			{
				// Add Query parameters
				pageType = pageType + '?';
				for (var count = 0; count < arrParentParams.length; count++) 
				{
					Pagetemp = arrParentParams[count].toString();
					IndexOfEqual = Pagetemp.indexOf('=');
					keyName = Pagetemp.substring(0, IndexOfEqual);
					keyValue = Pagetemp.substring(IndexOfEqual + 1);
													
					switch (keyName.toLowerCase()) 
					{						
						/*Added case - For development purpose as when 'refreshcache=1' is included in URL*/
						case 'refreshcache':
							break;
						/*Added case - To remove call to login success popup in MyMovies i.e. remove param if included in URL*/
						case 'showpopupcode':
							break;
						case 'search':
							// Add '&' for further query params
							if(count>0)
								pageType = pageType + "&";

							// Add KeyName as query param
							//Convert to standard capital format
							pageType = pageType + "Search=";

							// Add KeyValue as query param
							if(keyValue != '')
								pageType = pageType + keyValue;					
							else 
							{
								// 'hdnSearchString' store searched input string as page not maintaining that string in first and unmatched case
								if (varSearchVal != '')
								{
									pageType = pageType + varSearchVal; 
								}
							} 
							break;						
						default:	
							// Add '&' for further query params
							if(count>0)
								pageType = pageType + "&";
							// Add KeyName as query param
							pageType = pageType + keyName + "=";
							// Add KeyValue as query param
							pageType = pageType + keyValue;
							break;
					}

					//if(count == arrParentParams.length)
					//	break;
				}
			}
		}
				
		// Special case - For search page, if search param not present but there is value searched (happen in first time search scenario)
		if (varParentRelativeURL.indexOf("Search.aspx")>-1 && arrParentParams.length==0 && varSearchVal != '')
		{
			//if (varParentURL.search(/search=/i)> -1)
			//{
				pageType = pageType + "?Search=" + varSearchVal;
			//} 			
		}
		
		/* Special case : SamsungRevamp Detail page display - On button buy/rent click
															- To handle display of movie detail on page open i.e. Homepage, CategoryBrowsing, Search 
		Start */		
		//if (varParentRelativeURL=='/' || document.location.pathname.indexOf("CategoryBrowsing.aspx") > -1 || document.location.pathname.indexOf("Search.aspx") > -1)
		if (varParentRelativeURL == '/' || varParentRelativeURL.search(/categorybrowsing/i) > -1 || varParentRelativeURL.search(/search/i) > -1 || varParentRelativeURL.search(/home.aspx/i) > -1 || varParentRelativeURL.search(/Generic.aspx?type=homepage/i) > -1)
		{
			if (detailObject && detailObject.channelId != null) 
			{
				pageType = pageType + ',detailObject={"channelId":"' + detailObject.channelId + '","contentId":"' + detailObject.contentId + '",'
									+ '"channelName":"' + detailObject.channelName + '"}';				
			}
			else
			{			
				/* Special case : SamsungRevamp Detail page display - On button buy/rent click under movie payment process
																	- To handle display of movie detail on page open i.e. Homepage, CategoryBrowsing, Search 
				Start */	
				//If Detail object exists
				var pt=readCookie('_pType');
				var dObj;
				// Special case for redirecting to signsuccess only
				if (pt.indexOf(",") > -1 && popupUrl.indexOf("Generic.aspx?type=SignInSuccess") > -1)
				{			
					dObj=new Object();
					/*Save the detail object before deleting it from URL*/
					var strDetailObject=pt.substring(pt.indexOf('{'),pt.indexOf('}')+1);
					dObj=parseJSON(unescape(strDetailObject));					
				}
				// Get detail page info
				if (dObj && dObj.channelId != null) 
				{
					pageType = pageType + ',detailObject={"channelId":"' + dObj.channelId + '","contentId":"' + dObj.contentId + '",'
									+ '"channelName":"' + dObj.channelName + '"}';				
				}
			}
		}
	   /* Special case : SamsungRevamp Detail page display - End */
	/*}*/
	return pageType;
}

/*GET PARENT WINDOW TYPE*/

function showModalPopup(popupUrl, frameId, popupWidth, popupHeight, title, event) 
{
    if (title == null || title == '') {
        title = ''; 
    }

	/* Special case : SamsungRevamp Detail page display - On button buy/rent click under movie payment process
														- To handle display of movie detail on page open i.e. Homepage, CategoryBrowsing, Search 
		Start */	
	//Detail object exists
	var pt=readCookie('_pType');	

	// Special case for redirecting to signsuccess only
    //No detail object exists
	if (pt.indexOf(",") > -1 && popupUrl.indexOf("Generic.aspx?type=SignInSuccess") > -1);
	else
		//Erase Cookie which exists with value
		eraseCookie('_pType');


    /*General code	: To set '_pType' cookie on popup open (which will be deleted on popup close in hidemodalwindow)
	  Reason		: GET PARENT WINDOW TYPE : Fix for issue that on popup close or (X) click page is redirecting to homepage i.e. Issue #AT-1433*/	
	//Set page type of parent parent
	newCookie('_pType', setPageType(popupUrl), 1);  

	//Open jquery popup
    swsrPopup({url: popupUrl, frameId: frameId, title: title, height: popupHeight, width: popupWidth}, event);
};


function hideModalPopup(url, refresh) {
	closePopup(url, refresh);
}


function hideModalPopupFromInside(url, isPostback) {
	/* Get final parent page URL */
	var redirectPage = getReturnPageType();

	// Redirect to parent page URL through '_pType' cookie
	parent.parent.document.location.href = redirectPage;
	
	/* Special case : SamsungRevamp Detail page display - On button buy/rent click
														- To handle display of movie detail on page open i.e. Homepage, CategoryBrowsing, Search 
		Start */	
		/* Read page type cookie */	
	    redirectPage = readCookie('_pType');
		//No detail object exists delete as normal case
		if (redirectPage.indexOf(",") <= -1)
			// Erase Cookie which exists with value
			eraseCookie('_pType');
	/* Special case : SamsungRevamp Detail page display - End */

	// Close modal popup
	closePopupFromInside(url, isPostback);
}


/* //////////////////////////         Voucher Activate methods  ////////////////////    */

//******************Pagination.js funcions*********************//
function paginate(slider, points) {

    //clear page box
    $(points).getElements("a").each(function (e) {
        //e.remove();
        e.dispose();
    });
    var useFirst = true;
    $(slider).getChildren().getChildren()[0].each(function (page, index) {
        if (page.id == "currentChild") {
            useFirst = false;
        }
    });

    $(slider).getChildren().getChildren()[0].each(function (page, index) {
        var point = new Element('a', {
            'href': 'javascript: void new SimpleSlide(\'' + slider + '\',\'' + points + '\',{type: \'scroll\', goTo:' + (index + 1) + ', duration:400});',
            'class': 'page'
        });
        if (page.id == "currentChild" || (index == 0 && useFirst)) {
            point.addClass('active');
        } else {
            found = true;
        }
        $(points).adopt(point);
    });
}

/* function to set png-filter for ie6 */
function setPng24(obj) {
    obj.width = obj.height = 1;
    obj.className = obj.className.replace(/\bpng24\b/i, '');
    obj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + obj.src + "',sizingMethod='image');"
    obj.src = '';
    return '';
}

/* function to trim string */
function trim(str) {
    return str.replace(/^\s+/, '').replace(/\s+$/, '');
}

function parseResponse(responseText) {
    // normalize response
    responseText = responseText.replace(/\r\n/g, "\n");
    responseText = responseText.replace(/\n/g, " ");

    // match body
    var bodyPattern = /<body>\s*?(.+)\s*?<\/body/gi;
    bodyPattern.exec(responseText);

    // trim result
    var bodyText = trim(RegExp.$1);

    // match parts
    var messagePattern = /(.+)\s+(.+)/gi;
    messagePattern.exec(bodyText);

    // create return message
    var result = [];
    result[0] = RegExp.$1;
    result[1] = RegExp.$2;

    // check for error
    if (result[0] != "FILE") {
        result[0] = "ERROR";
        result[1] = bodyText;
    }

    return (result);
}

var ajax_handler=null;
var progress_handler=null;

function closeWindow() {
	if(ajax_handler!=null) {
       window.clearTimeout(ajax_handler);
    }
	$('#shaderBox').empty();
	$('#shaderBox').hide();
	$('#detailPageDiv').show();
}

// get query args
function getArgs(query) {
    var args = new Hash();
    if (!query) {
        var query = location.search.substring(1);
    }
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        args.set(argname, unescape(value));
    }
    return args;
}


// #################### VOUCHER REDEEM ##################
function redeemVoucher(event) {
    // check login
    
    if (document.getElementById('userid')) {
        var voucher_entry = $('#redeem_voucher');
        var voucher_msg = $('#redeem_voucher_message');
        var voucher_entry_text = $('#redeem_voucher').get(0).value;
        // clear previous message
        voucher_msg.innerHTML = "";

        // try to create voucher
        /*var RequestVoucher=new Request.HTML({
        url:'/RedeemVoucher.aspx',
        async:false,
        onSuccess:function(tr,elm,html,js) {
        voucher_msg.innerHTML=i18n_voucher_add;
        },
        onFailure:function(xhr) {
        if(xhr.status==399) {
        voucher_msg.innerHTML=i18n_voucher_error;
        }
        }                
        }).get({'voucherRef':voucher_entry.value});*/
		
		/*****Fix for issue#766 done on April 25,2011****/ 
		if(voucher_entry_text==''){
		    voucher_msg.get(0).innerHTML = varVoucherCode;
		  return;
		}
		/*****Fix for issue#766 done on April 25,2011****/ 
		
        $.get(
            "RedeemVoucher.aspx?voucherRef=" + voucher_entry_text,
		    {},
            function (xml) {
                var res = xml;
                
                //alert($(xml).find('response'));alert('hi');alert(res);}
                if ($(xml).get(0).nodeName == 'RESPONSE') {

                    if ($(xml).attr('result') == 'true') {
                        //						  alert("Success");
                        voucher_msg.get(0).innerHTML = varVoucher_successMsg;
                        showModalPopup('Generic.aspx?type=ActivateVoucherSuccess', 'frameId_SignIn', '645', '330', '', event);
                    }
                    else {
                        voucher_msg.get(0).innerHTML = varVoucher_errorMsg;
                        //						 alert("Fail");
                        // showModalPopup('Generic.aspx?type=ActivateVoucherSuccess', 'frameId_SignIn', '645', '330', '', this);
                    }

                }

            }
	 );
    } else {
        showModalPopup('Generic.aspx?type=Login', 'frameId_SignIn', '645', '400', '', event);
        // get length of parameter		
        //var args=getArgs();
        // sign in user
        //if(args.getLength()>0) {
        // window.location.href=document.getElementById('url_ce9fa761-5972-41ab-8419-7553a58ee0ed').href + "%26voucher=" + $('#redeem_voucher').get(0).value;
        //} else {
        // window.location.href=document.getElementById('url_ce9fa761-5972-41ab-8419-7553a58ee0ed').href + "%3Fvoucher=" + $('#redeem_voucher').get(0).value;
        //}
    }
}


//To be removed
function redeemVoucherCheck() {
    var voucher_entry = $('redeem_voucher');
    var voucher_activate = $('redeem_voucher_activate');

    // check for given voucher
    var args = getArgs();
    if (args.has('voucher')) {
        if (voucher_entry.value == "") {
            voucher_entry.value = args.get('voucher');
        }
    }

    // check length
    if (voucher_entry.value.length == 14) {
        // set color
        voucher_activate.setStyle('color', '#ff0000');
    } else {
        // set color
        voucher_activate.setStyle('color', '#666666');
    }
}

// ##################### OFFER HELPER ###################
// mapping-list


function delBasket(id) {
    // save to global scope
    offerId = id;

    // hide shader box
    $('shaderMessage').innerHTML = i18n_del_basket_message;
    $('shaderBox').style.opacity = 0.0;
    $('shaderBox').style.filter = 'alpha(opacity=0)';
    $('shaderBox').style.visibility = 'visible';
    $('shaderBox').style.top = '0px';
    $('shaderBox').style.left = '0px';
    $('shaderBox').style.height = parseInt(document.body.offsetHeight) + 'px';
    $('shaderBox').style.width = parseInt(document.body.offsetWidth) + 'px';
    $('shaderBox').set('tween', { duration: 'long' }).fade('hide');

    $('shaderBox').set('tween', {
        duration: 'long',
        onComplete: function () {
            // remove item from basket (syncronous)
            var RequestToBasket = new Request.HTML(
            {
                url: '/EditCart.aspx',
                async: false,
                onSuccess: function (tr, elm, html, js) {
                    window.location.href = 'ShoppingCart.aspx';
                    /*
                    $('shaderMessage').innerHTML='Your product has been removed from your shopping basket';
                    $('shaderBox').set('tween',{
                    duration:'long',
                    onComplete:function()
                    {
                    $('shaderMessage').innerHTML='Please wait...';
                    $('shaderBox').style.visibility='hidden';
                    $('shaderBox').style.top='0px';
                    $('shaderBox').style.left='0px';
                    $('shaderBox').style.width='1px';
                    $('shaderBox').style.height='1px';
                    window.location.href='ShoppingCart.aspx';
                    }
                    }).fade(0);
                    */
                },
                onFailure: function (xhr) {
                    if (xhr.status == 399) {
                        switch (xhr.getResponseHeader("Location")) {
                            case "Error.aspx?type=GeneralError":
                                $('shaderMessage').innerHTML = i18n_add_basket_generic_error;
                                break;
                        }

                        $('shaderBox').set('tween', {
                            duration: 'long',
                            onComplete: function () {
                                $('shaderMessage').innerHTML = i18n_wait_message;
                                $('shaderBox').style.visibility = 'hidden';
                                $('shaderBox').style.top = '0px';
                                $('shaderBox').style.left = '0px';
                                $('shaderBox').style.width = '1px';
                                $('shaderBox').style.height = '1px';
                                window.location.href = 'ShoppingCart.aspx';
                            }
                        }).fade(0);
                    }
                }
            }).get({ 'catalog': 'A', 'action': 'remove', 'offerId': offerId });
        }
    }).fade(0.8);
}
// ##################### OFFER HELPER ###################

function getYourVouchersOnLink() {
    var flagIf = false;
    var flagElse = false;
    i = 0;
    var total_balance = 0;
    var mycurrency = "";
    if (varxml == null) {
        $.ajax({
            type: "POST",
            async: false,
            url: "GetUserVouchers.aspx?filterByCurrency=true",
            dataType: "xml",
            data: { allvouchers: 1 },
            success: function (xml) {
                varxml = xml;
                $(".voucher_exmp_boxLink table").empty();
                mycurrency = $(xml).find('UserPaymentMethods').attr('currency');
                if (mycurrency == undefined)
                    mycurrency = "GBP";
                $(xml).find('voucher').each(function () {
                    var contentId = $(this).find('contentId').text();
                    var currency = $(this).find('currency').text();
                    var expirationDate = $(this).find('expirationDate').text();
                    var expirationDateFormated = new Date(expirationDate).format(DEFAULT_DATE_FORMAT)
                    var reference = $(this).find('reference').text();
                    var value = $(this).find('value').text();
                    var isTopUp = $(this).find('is_topup').text();
                    // convert to number
                    value = parseFloat(value) ? parseFloat(value).toFixed(2) : "0.00";
                    var state = $(this).find('state').text();
                    var type = $(this).find('type').text();
                    if (type == "") { type = "ALL"; }

                    value = value.replace(",", ".");
                    if (state == "new") {
                        total_balance += parseFloat(value);
                    }


                    if (isTopUp.toLowerCase() != 'true') {
                        if (flagIf != true) {
                            $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th>" + varVoucher_amount + " </th><th>" + varVoucher_expires + " </th><th>" + varVoucher_Type + " </th></tr>");
                            flagIf = true;
                        }
                        $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                        //$(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + varVoucher_voucher + " " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td><td>" + varVoucher_Type  + " " + type + "</td></tr>");
                    } else {
                        //$(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + varVoucher_myTopUpCredit + " " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td><td>" + varVoucher_Type  + " " + type + "</td></tr>");
                        if (flagElse != true) {
                            $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th>" + varVoucher_myTopUpCredit + " </th><th>" + varVoucher_expires + " </th><th>" + varVoucher_Type + " </th></tr>");
                            flagElse = true;
                        }
                        $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                    }
                    i = i + 1;
                });

            }
        });
    }
    else {
    $(".voucher_exmp_boxLink table").empty();
                mycurrency = $(varxml).find('UserPaymentMethods').attr('currency');
                if (mycurrency == undefined)
                    mycurrency = "GBP";
                $(varxml).find('voucher').each(function () {
                    var contentId = $(this).find('contentId').text();
                    var currency = $(this).find('currency').text();
                    var expirationDate = $(this).find('expirationDate').text();
                    var expirationDateFormated = new Date(expirationDate).format(DEFAULT_DATE_FORMAT)
                    var reference = $(this).find('reference').text();
                    var value = $(this).find('value').text();
                    var isTopUp = $(this).find('is_topup').text();
                    // convert to number
                    value = parseFloat(value) ? parseFloat(value).toFixed(2) : "0.00";
                    var state = $(this).find('state').text();
                    var type = $(this).find('type').text();
                    if (type == "") { type = "ALL"; }

                    value = value.replace(",", ".");
                    if (state == "new") {
                        total_balance += parseFloat(value);
                    }


                    if (isTopUp.toLowerCase() != 'true') {
                        if (flagIf != true) {
                            $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th>" + varVoucher_amount + " </th><th>" + varVoucher_expires + " </th><th>" + varVoucher_Type + " </th></tr>");
                            flagIf = true;
                        }
                        $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                        //$(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + varVoucher_voucher + " " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td><td>" + varVoucher_Type  + " " + type + "</td></tr>");
                    } else {
                        //$(".voucher_exmp_box table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + varVoucher_myTopUpCredit + " " + convertToCurrencySymbol(currency, value) + "</td><td>" + varVoucher_expires + " " + expirationDateFormated + "</td><td>" + varVoucher_Type  + " " + type + "</td></tr>");
                        if (flagElse != true) {
                            $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><th>" + varVoucher_myTopUpCredit + " </th><th>" + varVoucher_expires + " </th><th>" + varVoucher_Type + " </th></tr>");
                            flagElse = true;
                        }
                        $(".voucher_exmp_boxLink table").append("<tr class='" + state.toLowerCase() + " " + type.toUpperCase() + "'><td>" + convertToCurrencySymbol(currency, value) + " </td><td>" + expirationDateFormated + " </td><td>" + type + " </td></tr>");
                    }
                    i = i + 1;
                });

            }
    }


// ******************************* createXMLDocument ******************************* //

// Name: createXMLDocument
// Input: String
// Output: XML Document
function createXMLDocument(string) {
    var browserName = navigator.appName;
    var doc;
    if (browserName == 'Microsoft Internet Explorer') {
        doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.async = 'false'
        doc.loadXML(string);
    } else {
        doc = (new DOMParser()).parseFromString(string, 'text/xml');
    }
    return doc;
}


// *******************************createXMLDocument ******************************* //


// ******************************* Validate LOGIN ******************************* //
function validateUserLogin(parentPageType) {    
    var returnCode;
    var resultNode;
    var redirectPage;
    pdata = "Y";
    username = $("input[name=pw]").val();
    password1 = $("input[name=new_pw]").val();
    toRemember = $("input[name=rememberMe]");
    //if (toRemember.is(':checked')) { pdata = "Y"; }

    $.ajax({
        url: "LoginSamsung.aspx",
        type: "POST",
        data: { id: username, password: password1, p: pdata },
        success: function (xml) {
            responseXML = createXMLDocument(xml);
            resultNode = $(responseXML).children('result');
            resultNode.each(function () {
                returnCode = $(this).children('return').text();
            });

            if (returnCode == undefined) {
                returnCode = "100";
            }

			/* Special case: If user hits on user basket links i.e. MyMovies, MyAccount, Vouchers, AddCredit "without signin"  
										 on home/any other page then need to redirect it that part page
										 - Undefined if not initialised*/
			if(parentPageType != undefined && parentPageType != "")
			{
				//Erase Cookie which exists with value
				eraseCookie('_pType');

				switch (parentPageType) 
				{
					case 'MyMovies':
						//Set page type of parent parent
						newCookie('_pType', 'MyMovies.aspx?type=MyMoviesTVHP&filter=valid');
						break;
					case 'MyAccount':
						//Set page type of parent parent
						newCookie('_pType', 'Generic.aspx?type=MyInfo&tab=0');
						break;
					case 'Vouchers':
						//Set page type of parent parent
						newCookie('_pType', 'Generic.aspx?type=RedeemVoucher');
						break;
					case 'AddCredit':
						//Set page type of parent parent
						newCookie('_pType', 'Generic.aspx?type=MyInfo&tab=2');
						break;
					default:
						//Set page type of parent parent
						newCookie('_pType', 'Generic.aspx?type=homepage');
						break;
				}
			}
			
			// get final redirect page URL
			redirectPage = getReturnPageType();

            /*	Old code to read cookie - reduce code complexity in new function

            checkCatBrowsing = pagetype.search(/categorybrowsing/i);
            checkSearch = pagetype.search(/search/i);
            if (checkCatBrowsing > -1) {
                redirectPage = pagetype.split(",")[0];
            }
            else if (checkSearch > -1) {
                redirectPage = pagetype.split(",")[0];
            }
            else {
                if (pagetype == "" || pagetype.split('?')[1] == "") {
                    redirectPage = "generic.aspx?type=homepage";
                }
                else if (pagetype.indexOf(",") > -1) {
                    if (pagetype.indexOf("Home") > -1) {
                        //redirectPage=pagetype.split("=")[0].split(",")[0];
                        redirectPage = pagetype.split(",")[0];
                    }
                    else {
                        pagetype = pagetype.split(",")[0];
                        redirectPage = "Home.aspx" + pagetype;
                    }

                }
                else if (pagetype == "MyMovies") {
                    redirectPage = "MyMovies.aspx?filter=valid&type=MyMoviesTVHP";
                }
                else {
                    redirectPage = "generic.aspx?type=" + pagetype;
                }
            }
            if (redirectPage.indexOf("Home") > -1) {
                if (redirectPage.indexOf("=") > -1 || redirectPage.indexOf("&") > -1)// || window.location.search.substring(1).length > 0)
                    parent.parent.document.location.href = redirectPage + "&showPopUpCode=" + returnCode;
                else
                    parent.parent.document.location.href = redirectPage + "?showPopUpCode=" + returnCode;
            }
            else if (redirectPage.indexOf("Search") > -1) {
                if (redirectPage.indexOf("=") > -1 || redirectPage.indexOf("&") > -1)// || window.location.search.substring(1).length > 0)
                {
                    if (redirectPage.indexOf("search=") > -1 || redirectPage.indexOf("Search=") > -1) {
                        parent.parent.document.location.href = redirectPage + "&showPopUpCode=" + returnCode;
                    }
                    else {
                        parent.parent.document.location.href = redirectPage + "&search=&showPopUpCode=" + returnCode;
                    }
                }
                else
                    parent.parent.document.location.href = redirectPage + "?search=&showPopUpCode=" + returnCode;
            }
            else {
                parent.parent.document.location.href = redirectPage + "&showPopUpCode=" + returnCode;

            }*/

			 			

			if (redirectPage.indexOf("=") > -1 || redirectPage.indexOf("&") > -1)
				parent.parent.document.location.href = redirectPage + "&showPopUpCode=" + returnCode;
            else
				parent.parent.document.location.href = redirectPage + "?showPopUpCode=" + returnCode;			
        },
        error: function () {
            alert("Error");
        },
        complete: function () {
            //alert("Terminado");
        }
    });
}

function getReturnPageType()
{
	/* Read page type cookie */	
	var pagetype = readCookie('_pType');
            
	/* Special case : SamsungRevamp Detail page display - 
					  Remove detail object from URL as browser will not render it for pages i.e. Homepage, CategoryBrowsing, Search*/  
	var checkCatBrowsing = pagetype.search(/categorybrowsing/i);
    var checkSearch = pagetype.search(/search/i);
	var checkHome = pagetype.search(/home.aspx/i);
	if (checkHome <= -1)
	{
		checkHome = pagetype.search(/Generic.aspx?type=homepage/i);
	}	

	if (pagetype.indexOf(",") > -1)
	{
		//if (document.location.pathname=='/' || document.location.pathname.indexOf("CategoryBrowsing.aspx") > -1 || document.location.pathname.indexOf("Search.aspx") > -1)
		if (checkCatBrowsing > -1 || checkSearch > -1 || checkHome > -1)
			pagetype = pagetype.split(",")[0];
		else
			// Empty page points to homepage
			pagetype = "Home.aspx" + pagetype.split(",")[0];
	}	

	return pagetype;
}

function parseJSON(src) {
    if (typeof (JSON) == 'object' && JSON.parse)
        return JSON.parse(src);
    return eval("(" + src + ")");
}

// ******************************* Validate LOGIN ******************************* //


function openWindow(PurchaseId,VideoAssetId,ProgressBar,PageType) {
    ajax_retries=0;
    
	$('#shaderBox').empty();
    // check for selected device
    if(typeof(VideoAssetId) === 'undefined') {
        alert(varDeviceSelect);
        return;
    }

    // check browser
    if(!navigator.appName=="Microsoft Internet Explorer") {
        $('#steps_ie').hide();
        $('#steps_ff').show();
    } else {
        $('#steps_ie').show();
        $('#steps_ff').hide();
    }
    
    // set url for download
    var URL='/GetMovie.aspx';
    //Testing
	/*var URL='http://movies.uk.samsungapps.com/GetMovie.aspx?PurchaseID=C9EE08A3-7F71-4D60-ADF6-8524CF825CC7&VideoAssetID=E2902FF0-B529-4821-A8E6-97ECD6730CA6&TypeID=download&cache=1302781428311';   
	//PurchaseId='16257A85-41DC-4D34-85D8-62D859F1AF46';
	//VideoAssetId='8FDAC8D4-4874-46C1-83F9-F0C5957F92A5';*/
	
	// set max-left
    var max_left=555;

    // parse browser capabilities
    /*if(!PluginList.check('Windows Media Player') && (PageType=='vod_pc')) {
        PageType="dto_pc";
    }*/
    
    // check type to provide
    var type="";
    switch(PageType)
    {
        case "dto_mobile":
        case "dto_pc":
            type="download";
            break;
        case "vod_pc":
            type="stream";
            break;
    }
    $('#detailPageDiv').hide();//changed for work around of downloader ui to be displayed properly in abdence of promobanners
   	$('#download_page_message_' + PageType).html($('#download_page_wait').html());
	$('#shaderBox').removeAttr('class');
	//$('#download_page_' + PageType).find('div.box').hide();
	$('#shaderBox').html($('#download_page_' + PageType).html());
	$('#shaderBox').show();
	if(navigator.appName=="Microsoft Internet Explorer")
	$('#shaderBox').css.filter='alpha(opacity=85)';
	else 
	$('#shaderBox').css('opacity','85');
	$('#shaderBox').css('top','0px');
	$('#shaderBox').css('left','0px');
	$('#shaderBox').css('paddingTop', '0px');
    if (document.body.Height!=undefined && document.body.Width!=undefined)
    {
	$('#shaderBox').css('height',parseInt(document.body.Height) + 'px');
	$('#shaderBox').css('width',parseInt(document.body.Width) + 'px');
    }
    // hide links
    $('#download_page_link_href_stream').hide();
    $('#download_page_link_href_download').hide();

	// init progress-bar
	$('#progress_bar_' + PageType).show();
	$('#progress_bar_' + PageType).css('left','204px');
	$('#progress_bar_bg_' + PageType).removeAttr('complete');
	$('#progress_bar_bg_' + PageType).attr('class','loading');

	progress_handler=window.setInterval(function() {
		if(parseInt($('#progress_bar_' + PageType).css.left)<max_left) {
			$('#progress_bar_' + PageType).css.left=parseInt($('#progress_bar_' + PageType).css.left) + 1 + 'px';
		}
	},250);
        // call function for ajax
        openWindowAjax(progress_handler,URL,PageType,type,PurchaseId,VideoAssetId);
}


function openWindowAjax(progress_handler,url,PageType,type,PurchaseId,VideoAssetId){
	var timestamp=new Date().getTime();
	$.ajax({
	    url: url,
		data: {PurchaseID:PurchaseId,VideoAssetID:VideoAssetId,TypeID:type,cache:timestamp},
        type: "GET",
        success: function (resp) {
			var return_state="";
            var link="";
            
            // parse result
            //var result=parseResponse(resp);
			var result=$.trim(resp).split(' ');
            if(result.length<2) {
                return_state=result[0];
            } else {
                return_state=trim(result[0]);
                link=trim(result[1]);
                if(link.length==0) {
                    return_state="ERROR";
                }
            }
			switch(return_state) {
            case "FILE":
				switch(type){
				case "download":
					link=link.replace(host_msdrm,host_download);
				break;
				case "stream":
					link=link.replace(host_msdrm,host_stream);
				break;
			  }							
					$('#download_page_link_href_' + type).show();	
					$('#download_page_link_href_' + type).get(0).href=link;  
					$('#progress_bar_' + PageType).hide();
                    $('#progress_bar_bg_' + PageType).removeAttr('loading');
                    $('#progress_bar_bg_' + PageType).attr('class','complete');
					$('#download_page_message_' + PageType).html($('#download_page_link').html());	
			break;
            case "ERROR":
				// set message
				 // clear interval
                    window.clearInterval(progress_handler);
                    // set to full width
                    $('#progress_bar_' + PageType).css.left='0px';
                    $('#progress_bar_' + PageType).hide();
                    $('#progress_bar_bg_' + PageType).removeAttr('loading');
                    $('#progress_bar_bg_' + PageType).attr('class','complete');
					$('#download_page_message_' + PageType).html($('#download_page_link_error').html());
			break;
			case "PENDING":
			// check for number of retries
				if(ajax_retries<60) {
				ajax_retries++;
					ajax_handler=window.setTimeout(function() {
					openWindowAjax(progress_handler,url,PageType,type,PurchaseId,VideoAssetId);
					},10000);
				} 
				else{
					// clear interval
                        window.clearInterval(progress_handler);
                        // set to full width
                        $('#progress_bar_' + PageType).css.left='0px';
                        $('#progress_bar_' + PageType).hide();
                        $('#progress_bar_bg_' + PageType).removeAttr('loading');
                        $('#progress_bar_bg_' + PageType).attr('class','complete');

                        // set message
                        $('#download_page_message_' + PageType).html($('#download_page_link_error').html());
				}
			break;
		 }
				$('#shaderBox').empty();
				//$('#download_page_' + PageType).find('div.box').hide();	
				$('#shaderBox').html($('#download_page_' + PageType).html());
        },
        error: function () {
             window.clearInterval(progress_handler);
            
            // set to full width
            $('#progress_bar_' + PageType).css.left='0px';
            $('#progress_bar_' + PageType).hide();
            $('#progress_bar_bg_' + PageType).removeAttr('loading');
            $('#progress_bar_bg_' + PageType).attr('class','complete');

            // set message
            $('#download_page_message_' + PageType).html($('#download_page_link_error').html());
            $('#shaderBox').empty();
			//$('#download_page_' + PageType).find('div.box').hide();	
			$('#shaderBox').html($('#download_page_' + PageType).html());
        }
    });
}


